抽象工厂

动机:一系列相互依赖的对象创建,为了避开new所带来的紧耦合

数据库链接

public EmployeeDao{

	public static void main(String [] args){
		SqlConnection sqlc=new SqlConnection();
		SqlCommand sqlm=new SqlCommand();
		sqlm.setConnection(sqlc);
		SqlReader sqlr=sqlm.Excute();
		while(sqlr.read!=-1){
			...
		}
	}
}

将它利用工厂模式重构

class Connection{
	//基类方法
}
class ConnectionFactory{
	createConnect(...);
}

class Command{
	//基类方法
}
class CommandFactory{
	createCommand(...);
}

class Reader{
	//基类方法
}
class ReaderFactory{
	createReader(...);
}

class SqlConnection extends Connection implements ConnectionFactory{
	//继承基类
	@Override
	createConnect(...){
		return new SqlConnection();
	}
}

class SqlCommand extends Command implements CommandFactory{
	//继承基类
	@Override
	createCommand(...){
		return new SqlCommand();
	}
}

class SqlReader extends Reader implements ReaderFactory{
	//继承基类
	@Override
	createReader(...){
		return new SqlReader();
	}
}

public EmployeeDao{

	ConnectionFactory connectionFactory;
	CommandFactory commandFactoryl;
	ReaderFactory readerFactory;

	public static void main(String [] args){
		Connection sqlc=connectionFactory.createConnect(...);
		Command sqlm=commandFactoryl.createCommand(...);
		sqlm.setConnection(sqlc);
		Reader sqlr=sqlm.Excute();
		while(sqlr.read!=-1){
			...
		}
	}
}

但是这里虽然解决了表面上的耦合,也就是new,但是却忽略了三个对象之间的关系,它们之间是有联系的

class Connection{
	//基类方法
}
class Command{
	//基类方法
}
class Reader{
	//基类方法
}

class DBFactory{
	createConnect(...);
	createCommand(...);
	createReader(...);
}

class SqlConnection extends Connection implements DBFactory{
	//继承基类
	@Override
	createConnect(...){
		return new SqlConnection();
	}
}

class SqlCommand extends Command implements DBFactory{
	//继承基类
	@Override
	createCommand(...){
		return new SqlCommand();
	}
}

class SqlReader extends Reader implements DBFactory{
	//继承基类
	@Override
	createReader(...){
		return new SqlReader();
	}
}

public EmployeeDao{

	DBFactory dBFactory;

	public static void main(String [] args){
		Connection sqlc=dBFactory.createConnect(...);
		Command sqlm=dBFactory.createCommand(...);
		sqlm.setConnection(sqlc);
		Reader sqlr=sqlm.Excute();
		while(sqlr.read!=-1){
			...
		}
	}
}

同一个工厂就能够得到一个关联性的三个对象,不可能由于不同数据库平台而扰乱代码逻辑

你可能感兴趣的:(设计模式)