工厂模式

1.工厂模式概述

在工厂模式中,我们在创建对象时不会对客户端暴露创建逻辑,并且是通过使用一个共同的接口来指向新创建的对象。

优点:
(1)一个调用者想创建一个对象,只要知道其名称就可以了。
(2)扩展性高,如果想增加一个产品,只要扩展一个工厂类就可以。
(3)屏蔽产品的具体实现,调用者只关心产品的接口。
缺点:
每次增加一个产品时,都需要增加一个具体类和对象实现工厂,使得系统中类的个数成倍增加,在一定程度上增加了系统的复杂度,同时也增
加了系统具体类的依赖。

2.Java实现Demo

interface Shape {
    public void draw(); /*有无public都行*/
}

class Rectangle implements Shape {
    @Override
    public void draw() {
        System.out.println("Rectangle::draw()");
    }
}

class Scquare implements Shape {
    @Override
    public void draw() {
        System.out.println("Scquare::draw()");
    }
}


class ShapeeFactory {
    public Shape getShape(String shapeType) { /*返回的是公共父类(首先得有公共父类才行)接口*/
        if (shapeType == null) {
            return null;
        }

        if (shapeType.equalsIgnoreCase("rectangle")) {
            return new Rectangle();
        } else if (shapeType.equalsIgnoreCase("scquare")) {
            return new Scquare();
        }

        return null;
    }
}


public class FactoryPatternDemo {
    public static void main(String args[]) {
        ShapeeFactory factory = new ShapeeFactory();

        Shape rectangle = factory.getShape("rectangle"); /*接口虽然不能实例化对象,但是可以做左值接收实例化对象*/
        Shape scquare = factory.getShape("scquare");

        rectangle.draw();
        scquare.draw();
    }
}

3.C++实现Demo

#include <iostream>
#include <string.h>
using namespace std;

class Shape {
public:        //这里必须要指定public:,Java中的接口中指定不指定都行。
    virtual void draw() = 0; 
};

class Rectangle : public Shape {
public:
    void draw() {
        cout << "Rectangle::draw()" << endl;
    }
};

class Secquare : public Shape {
public:
    void draw() {
        cout << "Secquare::draw()" << endl;
    }
};

class ShapeFactory {
public:
    Shape* getShape(const char *shapeType) {
        if (shapeType == NULL) {
            return NULL;
        }
        if (!strcmp(shapeType, "rectangle")) {
            return new Rectangle();
        } else if (!strcmp(shapeType, "secquare")) {
            return new Secquare();
        }
        return NULL;
    }
};

int main() {
    ShapeFactory *factory = new ShapeFactory();

    Shape *rectangle = factory->getShape("rectangle");
    Shape *secquare = factory->getShape("secquare");

    rectangle->draw();
    secquare->draw();

    return 0;
}

参考:http://www.runoob.com/design-pattern/factory-pattern.html

原文地址:https://www.cnblogs.com/hellokitty2/p/10661925.html