工厂方法模式说明

use*_*364 6 asp.net design-patterns

我对工厂方法模式的理解是(如果我错了,请纠正我)

工厂方法模式

"工厂方法允许客户端将产品创建(实例创建)委托给子类".

我们可以通过两种方式创建Factory Method模式.

(i)当客户被限制为产品(实例)创建时.

(ii)有多种产品可供使用.但是决定需要退回哪个产品实例.

如果要创建抽象方法模式

  • 你需要有抽象的产品
  • 混凝土产品
  • Factory方法返回相应的产品.

示例:

public enum ORMChoice
{
  L2SQL,
  EFM,
  LS,
  Sonic
}
//Abstract Product
public interface IProduct
{
   void ProductTaken();
}
//Concrete Product
public class LinqtoSql : IProduct
{
  public void ProductTaken()
  {
    Console.WriteLine("OR Mapping Taken:LinqtoSql");
  }
 }
//concrete product
 public class Subsonic : IProduct
 {
    public void ProductTaken()
    {
       Console.WriteLine("OR Mapping Taken:Subsonic");
    }
 }
//concrete product
 public class EntityFramework : IProduct
 {
    public void ProductTaken()
    {
       Console.WriteLine("OR Mapping Taken:EntityFramework");
    }
  }
//concrete product
 public class LightSpeed : IProduct
 {
   public void ProductTaken()
   {
     Console.WriteLine("OR Mapping Taken :LightSpeed");
    }
  }

 public class Creator
 {
    //Factory Method 
    public IProduct ReturnORTool(ORMChoice choice)
    {
      switch (choice)
      {
        case ORMChoice.EFM:return new EntityFramework();
        break;
        case ORMChoice.L2SQL:return new LinqtoSql();
        break;
        case ORMChoice.LS:return new LightSpeed();
        break;
        case ORMChoice.Sonic:return new Subsonic();
        break;
        default: return null;
      }
  }

 }

**Client**

Button_Click()
{
 Creator c = new Creator();
 IProduct p = c.ReturnORTool(ORMChoice.L2SQL);
 p.ProductTaken();

}
Run Code Online (Sandbox Code Playgroud)

我对工厂方法的理解是否正确?

Bjö*_*lex 1

你所拥有的实际上更多的是一个抽象工厂模式,只是你的工厂(Creator)不是抽象的。因子方法模式对于子类化特别有用:

class A {
public:
    A() : m_Member( GetMember() ) 
    {
    }
protected:
    virtual ISomeInterface * GetMember() { // default impl here }
private:
    ISomeInterface * m_Member;
}
Run Code Online (Sandbox Code Playgroud)

现在 的子类A可以重写GetMember以使超类使用 的特定实现ISomeInterface