/*依赖倒置原则:抽象不应该依赖于实现细节,实现细节应该依赖于抽象。
* 即:若抽象A依赖于细节B,我们需要对细节B进行抽象得到抽象B,使得抽象A只依赖于抽象B,而细节B依赖于抽象B。
* 举例:人使用陶瓷水杯,现在需求变化为人要使用玻璃水杯,我们应该用:人依赖于水杯,而玻璃水杯和陶瓷水杯都依赖于水杯。
*
* 动机:面临“某些结构复杂的对象”的创建工作,由于需求的变化,这些对象经常面临剧烈的变化,但是他们却拥有稳定的接口。
* 目的:使客户程序隔离出这些易变对象。
*
* 场景:游戏中需要多种类型的人物角色,包括NormalActor[行走人物],FlyActor[飞行人物],WaterActor[潜水人物],而每中类型都会存在不同的子类型
* 如:NormalActor1,NormalActor2,FlyActor1,FlyActor2,WaterActor1等。
* 当需要添加新的具体类时,如WaterActor2,只需要增加该具体类即可,其他具体类的代码结构无需改变。
*/
//Actor.cs
public abstract class Actor
{
//对所有Actor的抽象,在prototye模式中没有使用
}
//NormalActor
public abstract class NormalActor : Actor
{
public abstract NormalActor clone();
}
public class NormalActor1 : NormalActor
{
public override NormalActor clone()
{
System.Console.WriteLine("Clone NormalActor1");
return (NormalActor)this.MemberwiseClone();
//MenberwiseClone是浅拷贝,即只是成员的复制,对于值类型可以完成。
//对于引用类型,可以通过序列化实现深拷贝
}
}
public class NormalActor2 : NormalActor
{
public override NormalActor clone()
{
System.Console.WriteLine("Clone NormalActor2");
return (NormalActor)this.MemberwiseClone();
}
}
public abstract class FlyActor : Actor
{
public abstract FlyActor clone();
}
public class FlyActor1 : FlyActor
{
public override FlyActor clone()
{
System.Console.WriteLine("Clone FlyActor1");
return (FlyActor)this.MemberwiseClone();
}
}
public class FlyActor2 : FlyActor
{
public override FlyActor clone()
{
System.Console.WriteLine("Clone FlyActor2");
return (FlyActor)this.MemberwiseClone();
}
}
public class FlyActor3 : FlyActor
{
public override FlyActor clone()
{
System.Console.WriteLine("Clone FlyActor3");
return (FlyActor)this.MemberwiseClone();
}
}
public abstract class WaterActor : Actor
{
public abstract WaterActor clone();
}
public class WaterActor1 : WaterActor
{
public override WaterActor clone()
{
System.Console.WriteLine("clone WaterActor1");
return (WaterActor)this.MemberwiseClone();
}
}
//GameSystem.cs
public class GameSystem
{
public void Operation(NormalActor nomalActor,FlyActor flyactor,WaterActor waterActor)
{
NormalActor normal1 = nomalActor.clone();
NormalActor normal2 = nomalActor.clone();
NormalActor normal3 = nomalActor.clone();
FlyActor fly1 = flyactor.clone();
FlyActor fly2 = flyactor.clone();
WaterActor water1 = waterActor.clone();
}
}
/*
*
*意图:使用原型实例指定创建对象的种类[原型实例指的是:NormalActor,FlyActor],
*
*
*/
class prototype
{
static void Main(string[] args)
{
GameSystem gs = new GameSystem();
NormalActor1 normal1 = new NormalActor1();
FlyActor2 fly2 = new FlyActor2();
WaterActor1 water1 = new WaterActor1();
gs.Operation(normal1, fly2, water1);
/*
* 输出:
* clone NormalActor1
* clone NormalActor1
* clone NormalActor1
* clone FlyActor2
* clone FlyActor2
* clone WaterActor1
*/
System.Console.WriteLine("end");
}
}