zoukankan      html  css  js  c++  java
  • 简单工厂模式_C#_设计模式

    基类:

     1 public class Operation
     2     {
     3         private int _numberA = 0;
     4         private int _numberB = 0;
     5         public int numberA
     6         {
     7             get { return _numberA; }
     8             set { _numberA = value; }
     9         }
    10         public int numberB
    11         {
    12             get { return _numberB; }
    13             set { _numberB = value; }
    14         }
    15         public virtual int OperationResult()
    16         {
    17             int result = 0;
    18             return result;
    19         }
    20     }


    实现了加法的子类:

    1  public class OperateAdd : Operation
    2     {
    3         public override int OperationResult()
    4         {
    5             int result = 0;
    6             result = numberA + numberB;
    7             return result;
    8         }
    9     }

    实现了减法的子类:

    1 public class OperareDuce : Operation
    2     {
    3         public override int OperationResult()
    4         {
    5             int result = 0;
    6             result = numberA - numberB;
    7             return result;
    8         }
    9     }

    工厂类OperationFactory:

     1 public class OperationFactory
     2     {
     3         public static Operation CreateOperation(string operate)
     4         {
     5             Operation ope = null;
     6             switch(operate)
     7             {
     8                 case "+":ope=new OperateAdd() ; break;
     9                 case "-": ope = new OperareDuce(); break;
    10             }
    11             return ope;
    12         }
    13     }

    调用:

    public static void Main()
            {
                Operation op = OperationFactory.CreateOperation("+");
                op.numberA = 1;
                op.numberB = 2;
                Console.WriteLine(op.OperationResult());
                Console.ReadKey();
            }

    父类中拥有共同所需的相关操作,子类对其进行重载,实现各自所需的操作。最后通过工厂类OperationFactory调用相关的子类

    刚开始学习设计模式,写的不好 轻点拍。

    代码参考来自《大话设计模式》

  • 相关阅读:
    Java 8 —— Lambda表达式
    Calendar 学习
    No provider available for the service com.xxx.xxx 错误解决
    ContextLoaderListener错误
    pom文件中引入依赖成功了,但是jar包找不着
    https=http+ssl
    Spring boot学习笔记
    Spring cloud 学习笔记
    记录一些注解的含义
    Linux笔记
  • 原文地址:https://www.cnblogs.com/steben/p/3087872.html
Copyright © 2011-2022 走看看