• 设计模式学习总结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();
                  }
                }
     
    }

    使用场景:

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

  • 相关阅读:
    图片热点 网页划区 网页的拼接 表单
    html body的属性 格式控制标签 内容容器标签 超链接标签 图片标签 表格
    结构体
    out 传值
    c#数组,手机号随机数抽奖
    输入月份和日期,输出是今年的第多少天,利用switch和case
    c#,for穷举,百鸡百钱
    c#条件运算符的使用,判断时间是上午还是下午
    c#关于try catch finally的使用,判断日期格式是否正确
    c#数组,例题
  • 原文地址:https://www.cnblogs.com/utopia/p/1675510.html
Copyright © 2020-2023  润新知