设计模式学习笔记五:抽象工厂模式

抽象工厂模式是工厂方法模式的进一步抽象,适用于有多个产品族的场景,拿美食举例:

美食可分为中餐和西餐,中餐又有东北菜,湘菜,粤菜等。而西餐又有法式菜、美式菜、德式菜等。这种可以称之为产品族。

个人认为抽象工厂顶级类应该都是单例的。

直接上代码了,代码与上面举例业务无关:

/**
 * @author liushijie
 *
 */
public class Run {
    public static void main(String[] args) {
        ProductFactory.getInstance().createPorductA1().create();
        ProductFactory.getInstance().createPorductB1().create();
        
        ProductFactory.getInstance().createPorductA2().create();
        ProductFactory.getInstance().createPorductB2().create();
    }
}

abstract class ProductAbstractFactory {
    public abstract IProductA createPorductA1();
    public abstract IProductA createPorductA2();
    public abstract IProductB createPorductB1();
    public abstract IProductB createPorductB2();
}

class ProductFactory extends ProductAbstractFactory {
    
    private static final ProductFactory facotry = new ProductFactory(); 
    
    private ProductFactory() {/*closed*/}

    public static ProductFactory getInstance() {
        return facotry;
    }
    
    @Override
    public IProductA createPorductA1() {
        return new ProductA1();
    }
    
    @Override
    public IProductA createPorductA2() {
        return new ProductA2();
    }
    
    @Override
    public IProductB createPorductB1() {
        return new ProductB1();
    }
    
    @Override
    public IProductB createPorductB2() {
        return new ProductB2();
    }
    
}

interface IProductA {
    void create();
}

interface IProductB {
    void create();
}
class ProductA1 implements IProductA {

    @Override
    public void create() {
        System.out.println("product A1");
    }    
}

class ProductA2 implements IProductA {

    @Override
    public void create() {
        System.out.println("product A2");
    }
    
}

class ProductB1 implements IProductB {

    @Override
    public void create() {
        System.out.println("product B1");
    }
}

class ProductB2 implements IProductB {

    @Override
    public void create() {
        System.out.println("product B2");
    }
    
}

 

posted @ 2015-01-25 06:10  土豆条  阅读(129)  评论(0编辑  收藏  举报