标签:des c style class blog code
工厂方法模式区别与简单工厂模式主要在于,factory中对对象的实例化延迟到了子类的factory中, 这也是优于简单工厂的地方。下面看这个模式的类图(截自《java与模式》):
示意性代码:
1
2
3
4
5
6
7 |
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类添加创建逻辑。
设计模式(三) : 创建型模式--工厂方法模式,布布扣,bubuko.com
标签:des c style class blog code
原文地址:http://www.cnblogs.com/ChristyorRuth/p/3758496.html