说明:给一个类增加额外的功能,适合使用,stream就是使用装饰者模式,有了MemoryStream,FileStream,NetworkStream等。
实现:
public abstract class car { public abstract void run(); } public class baoma : car { public override void run() { //实现方法 } } //我要加功能,用装饰者 public abstract class Decorator : car { private car c1; public Decorator(car carObj) { c1 = carObj; } public override void run() { if(c1!=null) { c1.run(); } } } //开始加,加个后视摄像头 public class Camera : Decorator { public Camera(car c1) :base(c1) { } public void addCamera() { //加后视摄像头 } public override void run() { base.run(); addCamera(); } } public class test { public void start() { car carObj = new baoma(); //加个摄像头 Decorator camera = new Camera(carObj); camera.run(); } }