简单工程模式

又叫 静态工厂模式

[ SimpleFactory ]

[ 创建型模式 ]

[ 角色: 工厂(Creator)角色 、抽象(Product)产品角色 、具体(Concrete Product)产品角色 ]

简单工厂模式的实质是由一个工厂类根据传入的参数,动态决定应该创建哪一个类的实例。



源码:

public interface IOperation
{
  int NumberA
  {
    get;
    set;
  }

  int NumberB
  {
    get;
    set;
  }

  int GetResult();
}



class OperationAdd : IOperation
{
  #region IOperation 成员

  private int _NumberA;
  private int _NumberB;

  public int NumberA
  {
    get
    {
      return _NumberA;
    }
    set
    {
      _NumberA = value;
    }
  }

  public int NumberB
  {
    get
    {
      return _NumberB;
    }
    set
    {
      _NumberB = value;
    }
  }

  public int GetResult()
  {
    return NumberA + NumberB;
  }

  #endregion
}



public class OperationDiv : IOperation
{
  #region IOperation 成员

  private int _NumberA;
  private int _NumberB;

  public int NumberA
  {
  get
  {
    return _NumberA;
  }
  set
  {
    _NumberA = value;
  }
  }

  public int NumberB
  {
    get
    {
      return _NumberB;
    }
    set
    {
      _NumberB = value;
    }
  }

  public int GetResult()
  {
    if (NumberB > 0)
    {
      return NumberA / NumberB;
    }
    else
    {
      return 0;
    }
  }

  #endregion
}



public class OperationFactory
{
  public static IOperation CreateOperation(string str)
  {
    switch(str)
    {
      case "+":
        return new OperationAdd();
        break;
      case "-":
        return new OperationSub();
        break;
      default:
        return new OperationAdd();
        break;
    }
  }
}



class Program
{
  static void Main(string[] args)
  {
    IOperation oper = OperationFactory.CreateOperation("+");
    oper.NumberA = 10;
    oper.NumberB = 11;
    Console.WriteLine(oper.GetResult());
    Console.ReadKey();
  }
}

你可能感兴趣的:(模式)