zoukankan      html  css  js  c++  java
  • Design Pattern ->Factory Method

    Layering & Contract Philosophy With additional indirection

    Factory Method

    The example code is as following:

     

     1 class CProduct //interface declaration
     2 class CConcreteProductOne: public CProduct;
     3 class CConcreteProductTwo: public CProduct;
     4 
     5 
     6 class CCreator
     7 {
     8      public: virtual CProduct* FactoryMethod()= 0;
     9 }
    10 class CConcreteCreator: public CCreator
    11 {
    12      public: CProduct* FactoryMethod(){ return new CConcreteProductOne()  OR  new CConcreteProductTwo()};
    13 }
    14 class CClient
    15 {  
    16         CCreator *pCreator = new CConreteCreator();
    17         CProduct *pProduct = pCreator->FacotryMethod();
    18 }

    IoC = Inversion Of Control.

    控制反转还有一个名字叫做依赖注入(Dependency Injection)。简称DI

    DIP = Dependence-Inversion Principle ( low-level module is depended on high-level module by defining abstract interface in high-level).

    Interface-Oriented Programming, not Implement-Oriented Programming

    Applicability
    Use the Factory Method pattern when

    •  A class can't anticipate the class of objects it must create.
    •  A class wants its subclasses to specify the objects it creates.
    • Classes delegate responsibility to one of several helper subclasses, and you want to localize the knowledge of which helper subclass is the delegate.
    • The new proper/appropriate instance of the concrete product can be got at run-time from the real situation.

    Participants

    • Product: defines the interface of objects the factory method creates.
    • ConcreteProduct : implements the Product interface.
    • Creator : declares the factory method, which returns an object of type Product.Creator may also define a default implementation of the factory method that returns a default ConcreteProduct object. may call the factory method to create a Product object.
    • ConcreteCreator: overrides the factory method to return an instance of a ConcreteProduct.

    Collaborations

    • Creator relies on its subclasses to define the factory method so that it returns an instance of the appropriate ConcreteProduct.
  • 相关阅读:
    Hihocoder 1275 扫地机器人 计算几何
    CodeForces 771C Bear and Tree Jumps 树形DP
    CodeForces 778D Parquet Re-laying 构造
    CodeForces 785E Anton and Permutation 分块
    CodeForces 785D Anton and School
    CodeForces 785C Anton and Fairy Tale 二分
    Hexo Next 接入 google AdSense 广告
    如何统计 Hexo 网站的访问地区和IP
    Design and Implementation of Global Path Planning System for Unmanned Surface Vehicle among Multiple Task Points
    通过ODBC接口访问人大金仓数据库
  • 原文地址:https://www.cnblogs.com/iiiDragon/p/3224322.html
Copyright © 2011-2022 走看看