赞
踩
相比于工厂方法模式,抽象工厂模式每个工厂可以生产多种产品(比如电影和书籍)。
实例
AbstractFactory.h
- #ifndef ABSTRACT_FACTORY_H_
- #define ABSTRACT_FACTORY_H_
-
- #include <memory>
- #include "AbstractProduct.h"
-
- class Factory {
- public:
- virtual std::shared_ptr<Movie> ProductMovie() = 0;
- virtual std::shared_ptr<Book> ProductBook() = 0;
- };
-
- #endif // ABSTRACT_FACTORY_H_
ConcreteFactory.h
- #ifndef CONCRETE_FACTORY_H_
- #define CONCRETE_FACTORY_H_
-
- #include <memory>
- #include "AbstractFactory.h"
- #include "ConcreteProduct.h"
-
- // 具体工厂类 中国生产者
- class ChineseProducer : public Factory {
- public:
- std::shared_ptr<Movie> ProductMovie() override {
- return std::make_shared<ChineseMovie>();
- }
-
- std::shared_ptr<Book> ProductBook() override {
- return std::make_shared<ChineseBook>();
- }
- };
-
- // 具体工厂类 日本生产者
- class JapaneseProducer : public Factory {
- public:
- std::shared_ptr<Movie> ProductMovie() override {
- return std::make_shared<JapaneseMovie>();
- }
-
- std::shared_ptr<Book> ProductBook() override {
- return std::make_shared<JapaneseBook>();
- }
- };
-
- #endif // CONCRETE_FACTORY_H_
AbstractProduct.h
- #ifndef ABSTRACT_PRODUCT_H_
- #define ABSTRACT_PRODUCT_H_
-
- #include <string>
-
- // 抽象产品类 电影
- class Movie {
- public:
- virtual std::string ShowMovieName() = 0;
- };
-
- // 抽象产品类 书籍
- class Book {
- public:
- virtual std::string ShowBookName() = 0;
- };
-
- #endif // ABSTRACT_PRODUCT_H_
ConcreteProduct.h
- #ifndef CONCRETE_PRODUCT_H_
- #define CONCRETE_PRODUCT_H_
-
- #include <iostream>
- #include <string>
- #include "AbstractProduct.h"
-
- // 具体产品类 电影::国产电影
- class ChineseMovie : public Movie {
- std::string ShowMovieName() override {
- return "《让子弹飞》";
- }
- };
-
- // 具体产品类 电影::日本电影
- class JapaneseMovie : public Movie {
- std::string ShowMovieName() override {
- return "《千与千寻》";
- }
- };
-
- // 具体产品类 书籍::国产书籍
- class ChineseBook : public Book {
- std::string ShowBookName() override {
- return "《三国演义》";
- }
- };
-
- // 具体产品类 书籍::日本书籍
- class JapaneseBook : public Book {
- std::string ShowBookName() override {
- return "《白夜行》";
- }
- };
-
- #endif // CONCRETE_PRODUCT_H_
main.cpp
- #include <iostream>
- #include "AbstractFactory.h"
- #include "ConcreteFactory.h"
-
-
- int main() {
- std::shared_ptr<Factory> factory;
-
- // 这里假设从配置中读到的是Chinese(运行时决定的)
- std::string conf = "China";
-
- // 程序根据当前配置或环境选择创建者的类型
- if (conf == "China") {
- factory = std::make_shared<ChineseProducer>();
- } else if (conf == "Japan") {
- factory = std::make_shared<JapaneseProducer>();
- } else {
- std::cout << "error conf" << std::endl;
- }
-
- std::shared_ptr<Movie> movie;
- std::shared_ptr<Book> book;
- movie = factory->ProductMovie();
- book = factory->ProductBook();
- std::cout << "获取一部电影: " << movie->ShowMovieName() << std::endl;
- std::cout << "获取一本书: " << book->ShowBookName() << std::endl;
- return 0;
- }
编译运行:
- $g++ -g main.cpp -o abstractfactory -std=c++11
- $./abstractfactory
- 获取一部电影: 《让子弹飞》
- 获取一本书: 《三国演义》
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。