Dependency inversion: abstraction should not depend on implementation details, implementation details should depend on abstraction [software analysis - software is dynamic]
Prototype mode
Intent
structure: Combined with examples to see
examples: scene, game system to create different roles
1. Abstract role class
public abstract class WalkPer
{
public abstract WalkPer clone();
}
public abstract class FlyPer
{
public abstract FlyPer clone();
}
2. Realization of specific roles
public class WalkPerA : WalkPer
{
public override WalkPer clone()
{
return (WalkPer)this.MemberwiseClone();
}
}
public class WalkPerB : WalkPer
{
public override WalkPer clone()
{
return (WalkPer)this.MemberwiseClone();
}
}
public class FlyPerA : FlyPer
{
public override FlyPer clone()
{
return (FlyPer)this.MemberwiseClone();
}
}
public class FlyPerB : FlyPer
{
public override FlyPer clone()
{
return (FlyPer)this.MemberwiseClone();
}
}
MemberwiseClone:
Copy by member (shallow copy: if the field is a value type, perform a bit-by-bit copy of the field. If the field is a reference type, copy the reference but not the referenced object. The original object and its copy refer to the same object!) 1. If its members are simple members (value type and string), this is no problem. When using the deep copy method, you must add a serializable identifier to the related class and the reference type of the class
: [ Serializable ] deep copy example code
/// <summary>
/// 通用的深拷贝方法
/// </summary>
/// <typeparam name="T"></typeparam>
[Serializable]//可序列化标识
public class BaseClone<T>
{
public virtual T Clone()
{
MemoryStream memoryStream = new MemoryStream();
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(memoryStream, this);
memoryStream.Position = 0;
return (T)formatter.Deserialize(memoryStream);
}
}
3. Game system (unchanged)
public class GameSystem
{
public void Run(WalkPer walkPer,FlyPer flyPer)
{
WalkPer walk1 = walkPer.clone();
WalkPer walk2 = walkPer.clone();
FlyPer fly1 = flyPer.clone();
FlyPer fly2 = flyPer.clone();
}
}
4. Call
public static void Main(string[] args)
{
GameSystem gameSystem = new GameSystem();
gameSystem.Run(new WalkPerA(),new FlyPerB());
}
Key points:
Creational mode summary: