简要说明

工厂方法通过一个抽象类实现了所有对产品的加工操作代码,唯独将产品的构建方法写成抽象方法。继承这个抽象类的具体类只重写其构建方法,这样就实现了对于不同被构建产品复用相同的加工操作逻辑。工厂方法适用于需要在子类中才能决定实例化哪个被操作对象,同时这些被操作对象又复用相同操作逻辑的场合。

结构类图

设计模式:03 工厂方法(Factory Method)

结构示例代码

/**************************************************
*

  • Design Pattren Quick Start
  • 03 FactoryMethod - 工厂方法

**************************************************/
namespace DesignPatternQuickStart.FactoryMethod
{
///
/// 产品接口
///
interface IProduct { }

///  
/// A类型产品 
///  
class ProductA : IProduct { } 

///  
/// B类型产品 
///  
class ProductB : IProduct { } 

///  
/// 含有工厂方法的抽象业务类 
///  
abstract class ACreator 
{ 
    protected abstract IProduct FactoryMethod(); 

    public void OpreateMethod() 
    { 
        IProduct product = FactoryMethod(); 
        //对product的一系列操作 
    } 
} 

///  
/// 生产A类型产品的具体业务类 
///  
class CreatorA : ACreator 
{ 
    protected override IProduct FactoryMethod() 
    { 
        return new ProductA(); 
    } 
} 

///  
/// 生产B类型产品的具体业务类 
///  
class CreatorB : ACreator 
{ 
    protected override IProduct FactoryMethod() 
    { 
        return new ProductB(); 
    } 
} 

///  
/// 客户类 
///  
class Client 
{ 
    public void OpreateMethod() 
    { 
        ACreator creatorA = new CreatorA(); 
        creatorA.OpreateMethod(); 

        ACreator creatorB = new CreatorB(); 
        creatorB.OpreateMethod(); 
    } 
} 

}

相关文章:

  • 2021-11-27
  • 2021-11-05
  • 2022-02-26
  • 2018-08-30
  • 2021-12-19
  • 2021-06-13
猜你喜欢
  • 2020-02-04
  • 2021-04-19
  • 2021-12-27
  • 2022-03-07
  • 2021-10-07
  • 2021-07-25
  • 2021-06-17
相关资源
相似解决方案