设计模式读书笔记之工厂方法模式(Factory method)

拿前面的简单工厂的例子作案例.把简单工厂改造成工厂方法.

//工厂接口
package designpattern.factory.factorymethod;
import designpattern.factory.*;
public interface IFactory {
	public UserDao createUserDao();
}
//DB2Dao工厂 
package designpattern.factory.factorymethod;
import designpattern.factory.*;
public class DB2DaoFactory implements IFactory{
	public UserDao createUserDao() {
		return new UserDB2Dao();
	}
}
//OracleDao工厂
package designpattern.factory.factorymethod;
import designpattern.factory.*;
public class OracleDaoFactory implements IFactory{
	public UserDao createUserDao() {
		return new UserOracleDao();
	}
}
//test case
package designpattern.factory.factorymethod;
import designpattern.factory.*;
public class Test {
	public static void main(String[] args) {
		IFactory f = new DB2DaoFactory();
		UserDao userDao = f.createUserDao();
		userDao.insert(new User());
		userDao.DeleteById("123456");
	}
}

特点: 有一个工厂序列, 工厂序列中各个工厂负责创建具体的对象.

与简单工厂的区别: 工厂方法把对象的实例化推迟到子类中. 把选择权交给客户代码来做.

 

 

你可能感兴趣的:(设计模式,F#,读书)