抽象工厂模式

60 阅读1分钟
/**
 * 抽象工厂模式
 * 个人理解:引入产品等级结构(如产品分为手机和电脑)和产品族(同一工厂创建的多个产品,如华为手机和华为电脑属于同一产品族)的概念,
 *  相比于工厂方法模式,工厂方法模式一个工厂只生产一个产品,抽象工厂方法一个工厂生产一族产品。
 * 组件:抽象工厂类(Factory)、具体工厂类(ConcreteFactory,本例中HuaWeiFactory、XiaoMiFactory)、
 *  抽象产品类(Product,本例中Cellphone、Computer),
 *  具体产品类(ConcreteProduct,本例中HuaweiCellphone、HuaweiComputer、XiaoMiCellphone、XiaoMiComputer)、客户类(Client)
 * 注意点:需要客户端选择需要调用的具体工厂和具体产品方法
 *
 */
public class AbstractFactoryDesignPattern {

    public static void main(String[] args) {
        Cellphone cellphone = new HuaWeiFactory().createCellphone();
        cellphone.display();
    }
}


interface Factory {

    /**
     * 生产手机
     */
    Cellphone createCellphone();

    /**
     * 生产电脑
     */
    Computer createComputer();
}


class HuaWeiFactory implements Factory {

    @Override
    public Cellphone createCellphone() {
        return new HuaweiCellphone();
    }

    @Override
    public Computer createComputer() {
        return new HuaweiComputer();
    }
}

class XiaoMiFactory implements Factory{

    @Override
    public Cellphone createCellphone() {
        return new XiaoMiCellphone();
    }

    @Override
    public Computer createComputer() {
        return new XiaoMiComputer();
    }
}

interface Cellphone {
    void display();
}

interface Computer {
    void display();
}

class HuaweiCellphone implements Cellphone {

    @Override
    public void display() {
        System.out.println("This is HuaWeiCellphone");
    }
}

class XiaoMiCellphone implements Cellphone {

    @Override
    public void display() {
        System.out.println("This is XiaoMiCellphone");
    }
}

class HuaweiComputer implements Computer {

    @Override
    public void display() {
        System.out.println("This is HuaWeiComputer");
    }
}

class XiaoMiComputer implements Computer {

    @Override
    public void display() {
        System.out.println("This is XiaoMiComputer");
    }
}