简单工厂
用一个类来实例类
1.一个计算器的类有两个属性,为number1和number2
2.一个virtual方法用来得到结果
3.在工厂类中根据用户的操作符类型决定具体实例化哪个类
用例:
用面向对象的思想实现一个计算器
class Program
{
static void Main(string[] args)
{
Opearation myOpearation = CreateOp.MCreateOp("+");
myOpearation.Number1 = 10;
myOpearation.Number2 = 20;
Console.Write(myOpearation.GetResult());
}
}
public abstract class Opearation
{
private float number1;
private float number2;
protected float result;
public float Number1 { get => number1; set => number1 = value; }
public float Number2 { get => number2; set => number2 = value; }
public virtual float GetResult()
{
result = 0;
return result;
}
}
public class AddOpearation : Opearation
{
public override float GetResult()
{
result = Number1+Number2;
return result;
}
}
public class SubOpearation : Opearation
{
public override float GetResult()
{
result = Number1 - Number2;
return result;
}
}
public class CreateOp
{
public static Opearation MCreateOp(string mopearation)
{
switch (mopearation)
{
case "+":
{
return new AddOpearation();
}
case "-":
{
return new SubOpearation();
}
default:
{
break;
}
}
return null;
}
}
工厂模式
工厂模式将用一个类来对一个类实例化,这些实例化的类继承一个抽象的实例化类。这种模式避免了简单工厂中的switch、case的情况,在具体需要实例一个类的时候,调用某一个类就可以
让一个类的实例化延迟到其子类。
class Program
{
static void Main(string[] args)
{
IFoodFactory cookFishPork = new CookFishPork();
Food food = cookFishPork.Cooking();
}
}
interface IFoodFactory
{
Food Cooking();
}
class CookFishPork : IFoodFactory
{
public Food Cooking()
{
return new FishFlavoredPork();
}
}
class CookBraisedPork : IFoodFactory
{
public Food Cooking()
{
return new BraisedPork();
}
}
abstract class Food
{
public virtual void myname()
{
Console.WriteLine("food");
}
}
class FishFlavoredPork : Food
{
public override void myname()
{
Console.WriteLine("fishPork");
}
}
class BraisedPork : Food
{
}
网友评论