设计模式DP(1)工厂方法
设计模式DP(1)工厂方法FactoryMethod
特点:一个类的实例化具体到让子类去实例化
根据不同的类型,实例化特定的接口
向上兼容性
代码:
##定义任务工作接口
public inte易做图ce IWork{
public void doWork();
}
public class FatherWork implements IWork{
public void doWork(){
System.out.println("Father do work");
}
}
public class SonWork implements IWork{
public void doWork(){
System.out.println("Son do work");
}
}
##定义工厂方法
public inte易做图ce IFactory{
public IWork getWork();
}
public class FatherFactory implements IFactory{
public IWork getWork(){
return new FatherWork();
} www.zzzyk.com
}
public class SonFactory implements IFactory{
public IWork getWork(){
return new SonWork();
}
}
##下面测试一下
public static void main(String[] args){
IFactory factory1 = new FatherFactory();
factory1.getWork().doWork();
IFactory factory2 = new SonFactory();
factory2.getWork().doWork();
}
##输出结果
Father do work
Son do work
补充:软件开发 , Java ,