设计模式学习总结3 创建型3 FactoryMethod工厂方法模式

 FactoryMethod工厂方法模式(创建型)


作用:

工厂方法模式是一种创建型模式,它是由子类来决定实例哪个类,多个子类都实现了接口,工厂方法根据客户端或当前状态的外部提供的信息实例化对应的子类。

Role
The  Factory  Method  pattern  is  a  way  of  creating  objects,  but  letting  subclasses decide exactly which class to instantiate. Various subclasses might implement the interface; the Factory Method instantiates the appropriate subclass based on infor-
mation supplied by the client or extracted from the current state.

设计:

IProduct,要实例化子类的接口
ProductA and ProductB,实现了IProduct接口的子类
ProductFactory,提供工厂方法来实例化所需的子类
CreateProduct,决定实例化哪个子类

举例:

ProductFactory,钢笔店 
CreateProduct,根据客户要求提供各类钢笔
ProductA,英雄钢笔
ProductB,永生钢笔
IProduct,钢笔的规范:书写,加墨
实现:

代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace FactoryMethod
{

   
class Program
    {

        
static void Main(string[] args)
        {
              Creator c 
= new Creator();
              IProduct product;

              
for (int i=1; i<=12; i++
              {
                product 
= c.FactoryMethod(i);
                Console.WriteLine(
"Avocados "+product.ShipFrom());
              }
        }
    }


             
// Factory Method Pattern           Judith Bishop  2006
             interface IProduct {
              
string ShipFrom();
             }

            
class ProductA : IProduct {
              
public String ShipFrom () {
                
return " from South Africa";
              }
            }

            
class ProductB : IProduct {
              
public String ShipFrom () {
                
return "from Spain";
              }
            }

            
class DefaultProduct : IProduct {
              
public String ShipFrom () {
                
return "not available";
              }
            }

            
class Creator {
              
public IProduct FactoryMethod(int month) {
                
if (month >= 4 && month <=11)
                    
return new ProductA();
                
else
                
if (month == 1 || month == 2 || month == 12)
                    
return new ProductB();
                
else return new DefaultProduct();
              }
            }
 
}

使用场景:

当系统中灵活性非常重要;
由工厂方法来决定选择哪个子类;

原文地址:https://www.cnblogs.com/utopia/p/1675510.html