zoukankan      html  css  js  c++  java
  • 设计模式——工厂方法模式(Factory Method)

    • 创建一工厂接口,实例化延迟至子类(添加新对象,只需增加新的工厂子类)
    • 解决简单工厂违反开闭原则的问题
    • 代码示例:
       1 #include <iostream>
       2 #include <string>
       3 using namespace std;
       4 
       5 //product
       6 class Shape 
       7 {
       8 public:
       9     virtual void draw() = 0;
      10     virtual ~Shape() {}
      11 };
      12 
      13 class Circle : public Shape 
      14 {
      15 public:
      16     void draw() { cout << "Circle::draw" << endl; }
      17     ~Circle() { cout << "Circle::~Circle" << endl; }
      18 private:
      19     Circle() {}
      20     friend class CircleFactory;
      21 };
      22 
      23 class Square : public Shape 
      24 {
      25 public:
      26     void draw() { cout << "Square::draw" << endl; }
      27     ~Square() { cout << "Square::~Square" << endl; }
      28 private:
      29     Square() {}
      30     friend class SqureFactory;
      31 };
      32 
      33 //factory
      34 class Factory
      35 {
      36 public:
      37     virtual Shape* create() = 0;
      38 };
      39 
      40 class CircleFactory : public Factory
      41 {
      42 public:
      43     Shape* create(){return new Circle;}
      44 };
      45 
      46 class SqureFactory : public Factory
      47 {
      48 public:
      49     Shape* create(){return new Square;}
      50 };
      51 
      52 int main() 
      53 {
      54     Factory *pFactory = new CircleFactory;//SqureFactory;
      55 
      56     Shape* pShape = pFactory->create();
      57 
      58     pShape->draw();
      59 
      60     delete pShape;
      61     delete pFactory;
      62 
      63     return 0;
      64 }
  • 相关阅读:
    leetcode 18 4Sum
    leetcode 71 Simplify Path
    leetcode 10 Regular Expression Matching
    leetcode 30 Substring with Concatenation of All Words
    leetcode 355 Design Twitte
    leetcode LRU Cache
    leetcode 3Sum
    leetcode Letter Combinations of a Phone Number
    leetcode Remove Nth Node From End of List
    leetcode Valid Parentheses
  • 原文地址:https://www.cnblogs.com/dahai/p/2840390.html
Copyright © 2011-2022 走看看