工厂方法模式(factory method pattern)从2方面认识。
编程技巧:这是对参数化工厂方法加以改进的经典技术,以多态来重构if-else、switch-case等分支结构。
设计思路:你一定要注意,工厂方法模式中Client关注的不是的产品(所以静态工厂中Door的例子,不适合),Client关注的是工厂!
package creational.factory;
public class DoorFactory{
public static Door getObject(String typeName) {//int ID
if(typeName.equals("D1")){
return new D1();
}else if(typeName.equals("D2")){
return new D2();
}else{
return null;
}
}
}
package creational.factory;
public class Hand{
static Door d = null;
public static void test(){
d = DoorFactory.getObject("D2") ;
d.m();
}
}
在不使用配置文件和反射机制的情况下,interface IDoorFactory {
public Door createDoor();
}
class D1Factory implements IDoorFactory {
public D1 createDoor() {
return new D1();
}
}//D2Factory 略
public class Client {
public static void main(String[] args) {
IDoorFactory factory = new D1Factory();
Door door= factory.createDoor();//生产D1
door.m();
}
}
将工厂类泛化成抽象类型,以其子类多态地创建不同的产品如Door的子类。interface ICar{ //工厂接口
public I4S get4S();//管你是那个4S店
public void move();
}
class BBCar implements ICar{
public I4S get4S() {
return new BB4S();
}
public void move(){
System.out.println("BBCar move");
}
}//QQCar 略
interface I4S{
void doShomthing();
}//实现类略
public class Client{
public static void main(String[] args) {
ICar car =new BBCar();
car.move();
I4S repair = car.get4S();
repair.doShomthing();
car.move();
}
}public interface Iterable{
Iterator iterator();//返回一个迭代器
}原文地址:http://blog.csdn.net/yqj2065/article/details/39229481