设计模式(三) : 创建型模式--工厂方法模式

工厂方法模式区别与简单工厂模式主要在于,factory中对对象的实例化延迟到了子类的factory中, 这也是优于简单工厂的地方。下面看这个模式的类图(截自《java与模式》):

示意性代码:

package com.javadesignpattern.factorymethod;

public interface Creator {
	
	public Product fatcory();

}

  

package com.javadesignpattern.factorymethod;

public interface Product {
    

}
package com.javadesignpattern.factorymethod;

public class ConcreteCreator1 implements Creator{

    public Product fatcory() {
        // TODO Auto-generated method stub
        return new ConcreteProduct1();
    }

}
package com.javadesignpattern.factorymethod;

public class ConcreteCreator2 implements Creator {

    public Product fatcory() {
        // TODO Auto-generated method stub
        return new ConcreteProduct2();
    }

}
package com.javadesignpattern.factorymethod;

public class ConcreteProduct1 implements Product{

}
package com.javadesignpattern.factorymethod;

public class ConcreteProduct2 implements Product{

}
package com.javadesignpattern.factorymethod;

public class Client {
    
    
    public static void main(String[] args){
        Creator creator1 = new ConcreteCreator1();
        Product product1 = creator1.fatcory();
        Creator creator2 = new ConcreteCreator2();
        Product product2 = creator2.fatcory();
    }

}

优点:

1. 创建逻辑从客户端独立出来,实现了创建逻辑和其余的逻辑的解耦。

2. 扩展性好:如果我们需要新加一个工厂类的实现的话,原来的代码不需要动,只需要新加一个factory类添加创建逻辑。

posted @ 2014-05-29 10:11  Ruth/Christy  阅读(101)  评论(0编辑  收藏