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);
    	}
    
    }
    
     
  • 相关阅读:
    BZOJ 3669 & luogu 2387 魔法森林
    caioj 2064 & POJ 1741 & CH 0x40数据结构进阶(0x45 点分治)例题1:树
    caioj 2063& CH 0x40数据结构进阶(0x44 分块)例题4:小Z的袜子
    BZOJ 2154: Crash的数字表格
    追查坏牛奶(最大流)
    [JLOI2014]松鼠的新家
    [HAOI2015]树上操作
    [NOI2015]软件包管理器(树链刨分)
    [JSOI2008]球形空间产生器(高斯消元)
    [ZJOI2008]树的统计(树链刨分)
  • 原文地址:https://www.cnblogs.com/hellozzz/p/4654773.html
Copyright © 2011-2022 走看看