设计模式

工厂模式

2017-02-14  本文已影响15人  CodingHou

定义:定义一个用于创建对象的接口,让子类决定实例化哪个类,工厂类将一个类的实例化延迟到其子类。
类型:创建类模式

interface IProduct {  
    public void productMethod();  
}  
  
class Product implements IProduct {  
    public void productMethod() {  
        System.out.println("产品");  
    }  
}  
  
interface IFactory {  
    public IProduct createProduct();  
}  
  
class Factory implements IFactory {  
    public IProduct createProduct() {  
        return new Product();  
    }  
}  
  
public class Client {  
    public static void main(String[] args) {  
        IFactory factory = new Factory();  
        IProduct prodect = factory.createProduct();  
        prodect.productMethod();  
    }  
}  

工厂模式:
首先需要说一下工厂模式。工厂模式根据抽象程度的不同分为三种:简单工厂模式(也叫静态工厂模式)、本文所讲述的工厂方法模式、以及抽象工厂模式。工厂模式是编程中经常用到的一种模式。它的主要优点有:

工厂方法模式:

通过工厂方法模式的类图可以看到,工厂方法模式有四个要素:

前文提到的简单工厂模式跟工厂方法模式极为相似,区别是:简单工厂只有三个要素,他没有工厂接口,并且得到产品的方法一般是静态的。因为没有工厂接口,所以在工厂实现的扩展性方面稍弱,可以算所工厂方法模式的简化版,关于简单工厂模式,在此一笔带过。

上一篇 下一篇

猜你喜欢

热点阅读