设计模式之工厂方法模式

2018-08-11  本文已影响10人  tanoak

在上篇文章中我们探讨了简单工厂的好处,那么工厂方法模式比简单工厂有什么优势呢?

public class Apple implements Fruit {

    @Override
    public void color() {
        System.out.println("this is Apple ,color Red");
    }
}

public class AppleCreator implements Creator {

    @Override
    public Fruit createFruit() {
        return new Apple() ;
    }
}

public class Pear implements Fruit {
    @Override
    public void color() {
        System.out.println("this is pear ,color yellow");
    }
}

public class PearCreator implements Creator {

    @Override
    public Fruit createFruit() {
        return new Pear() ;
    }
}

public interface Creator {

    /**
     *  创建 Fruit
     * @return Fruit
     */
    Fruit createFruit();
}

package com.tanoak.create.factory.method;

public interface Fruit {
    /**
     * 水果颜色
     */
    void color();
}
package com.tanoak.create.factory.method;
public class Main {
    public static void main(String[] args) {
        /*
        Creator buldCreator = new AppleCreator();
        Fruit fruit = buldCreator.createFruit();
        fruit.color();*/

        Creator creator = new PearCreator();
        Fruit fruit = creator.createFruit();
        fruit.color();
    }
}

简单理解成小明今天想吃苹果=>指定苹果产品=>通知水果工厂生产

UML类图如下


归根到底 工厂方法模式是因为简单工厂模式违反“开闭原则”而创立的,两个模式对比可以加深理解

上一篇 下一篇

猜你喜欢

热点阅读