zoukankan      html  css  js  c++  java
  • 工厂模式

    定义一个用户创建对象的接口,让子类决定实例化哪一个

    image_2

    1.产品

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


    2.工厂

    每个产品都有一个工厂

    interface IProductFactory
     {
         IProduct FactoryMethod();
     }
     
     class ProductFactoryA :IProductFactory
     {
         public IProduct FactoryMethod()
         {
             return new ProductA();
         }
     }
     
     class ProductFactoryB : IProductFactory
     {
         public IProduct FactoryMethod()
         {
             return new ProductB();
         }
     }


    3.客户端调用

    IProductFactory factory = new ProductFactoryA();
     IProduct Product;
     Product = factory.FactoryMethod();
     factory = new ProductFactoryB();
     Product = factory.FactoryMethod();

    与工厂模式比较,这里每个产品都有工厂,虽有扩展性,但每个产品都有工厂也造成了麻烦

  • 相关阅读:
    缺少一个=出现的问题
    快速排序+归并排序
    ACwing简单题(14)
    浅谈#ifndef
    fstream 使用详解
    _stat函数的使用
    关于文件结构体的使用
    new的使用
    ACwing13题目
    ACwing13题
  • 原文地址:https://www.cnblogs.com/Clingingboy/p/1809554.html
Copyright © 2011-2022 走看看