设计模式之 - 简单工厂模式(实例)

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

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

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

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

 

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);
	}

}

 

 

posted on 2015-07-17 15:50  快要结束了  阅读(224)  评论(0编辑  收藏  举报

导航