工厂方法模式

时间:2022-10-02 12:09:02

汽车工厂接口:

public interface Factory {
	public Car createCar();

}

oracle工厂

public class OracleFactory implements Factory{


	@Override
	public DataBase createCar() {
		String ip="192.168.1.102";
		String port = "1433";
		String username= "root";
		String passowrd= "654321";
		DataBase db = new Oracle(ip,port,username,passowrd);
		return db;
	}
}
mysql工厂
public class MySqlFactory implements Factory{
	@Override
	public DataBase createCar() {
		String ip="192.168.1.101";
		String port = "3306";
		String username= "root";
		String passowrd= "123456";
		DataBase db = new Mysql(ip,port,username,passowrd);
		return db;
	}

}

连接数据库接口

public interface DataBase {
	public void connect();
}

Oracle数据库

public class Oracle implements DataBase{
	private String ip;
	private String port;
	private String username;
	private String password;
	
	public Oracle(String ip,String port,String username,String passowrd){
		this.ip = ip;
		this.port = port;
		this.username = username;
		this.password = password;
	}
	
	@Override
	public void connect() {
		System.out.println("oracle 连接成功!ip:"+this.ip);
	}
}

mysql 数据库

public class Mysql implements DataBase{
	private String ip;
	private String port;
	private String username;
	private String password;
	
	public Mysql(String ip,String port,String username,String passowrd){
		this.ip = ip;
		this.port = port;
		this.username = username;
		this.password = password;
	}

	@Override
	public void connect() {
		System.out.println("mysql 连接成功!ip:"+this.ip);
	}


}

客户端1

public class Client {


	public static void main(String a[]){
		Factory factory1 = new MySqlFactory();
		DataBase car1 = factory1.createCar();
		car1.connect();
		
		Factory factory2 = new OracleFactory();
		DataBase car2 = factory2.createCar();
		car2.connect();
	}
}

客户端2

public class Clinet2 {

	public static void main(String a[]){
		Factory factory1 = new MySqlFactory();
		DataBase car1 = factory1.createCar();
		car1.connect();
		
		Factory factory2 = new OracleFactory();
		DataBase car2 = factory2.createCar();
		car2.connect();
	}
}

以上就是工厂模式常见的实现方式,下面就总结下我认为的一些好处:

1、将对象的创建逻辑进行了封装,以后如果需要改创建逻辑,只需要跑到对应的工厂类里面做修改就行了,比如上面例子有多个客户端获取数据库连接,当数据库ip 或者账号 密码等变动时只要在工厂类里面修改就行了

2、