zoukankan      html  css  js  c++  java
  • 设计模式之

    一个简单的计算器栗子,  计算值和结果是固定的, 运算过程是根据需求变化的。

    工厂模式一般适用于: 若干具有相同父类的子类, 并且需要重复做一件事情的时候,

    所以顾名思义叫做工厂模式, 重复的东西全让工厂做了~

    现在只是明白原理,但是还没真正在项目中实践过, 心得会不断的更新的

    using UnityEngine;
    using System.Collections;
    
    
    public class Opration
    {
    	public double NumberA{get;set;}
    	public double NumberB{get;set;}
    
    	public virtual double GetResult ()
    	{
    		double result = 0f;
    		return result;
    	}
    }
    
    public class OprationAdd:Opration
    {
    	public override double GetResult()
    	{
    		double result = 0f;
    		result = NumberA + NumberB;
    		return result;
    	}
    }
    
    public class OprationSub:Opration
    {
    	public override double GetResult()
    	{
    		double result = 0f;
    		result = NumberA - NumberB;
    		return result;
    	}
    }
    
    public class OprationMul:Opration
    {
    	public override double GetResult()
    	{
    		double result = 0f;
    		result = NumberA * NumberB;
    		return result;
    	}
    }
    
    public class OprationDiv:Opration
    {
    	public override double GetResult()
    	{
    		double result = 0f;
    
    		if (NumberB == 0)
    			throw new UnityException ("除数不能为0");
    
    		result = NumberA / NumberB;
    		return result;
    	}
    }
    
    public class OprationFactor
    {
    	public static Opration CreateOptation(string opa)
    	{
    
    		Opration opration = null;
    
    		switch(opa)
    		{
    			case  "+":
    				opration = new OprationAdd();
    				break;
    
    			case  "-":
    				opration = new OprationSub();
    				break;
    
    			case  "*":
    				opration = new OprationMul();
    				break;
    
    			case  "/":
    				opration = new OprationDiv();
    				break;
    		}
    
    		return opration;
    	}
    }
    
    public class NewBehaviourScript : MonoBehaviour 
    {
    	
    	void Start () 
    	{
    		Opration op = OprationFactor.CreateOptation ("/");
    		op.NumberA = 10;
    		op.NumberB = 20;
    		double result = op.GetResult ();
    		Debug.Log ("the result is " + result);
    	}
    
    }
    
     
  • 相关阅读:
    发布一个用于WinCE的矢量图控件
    [非原创]树和图的遍历
    对ZOJ第1146题的解答:LCDisplay
    [c#]可在任意位置弹出的BalloonTip
    windows程序开发中c++和c#的对照
    关于编译时的warning treated as error
    flyweight模式和图元几何变换
    i++和++i作为参数时的编译器处理方式分析~
    用小数数组计算E值(对ZOJ第1113题的解答)
    显示SendMessage和PostMessage的区别
  • 原文地址:https://www.cnblogs.com/hellozzz/p/4654773.html
Copyright © 2011-2022 走看看