C#設計模式-裝飾者模式
阿新 • • 發佈:2018-12-18
using System; using System.Collections.Generic; namespace TestCS { class Program { static void Main(string[] args) { Robot robot = new DanceRobot(); robot.Perform(); robot = new JumpDecorator(robot); robot.Perform(); robot = new SingDecorator(robot); robot.Perform(); Console.ReadKey(); } abstract class Robot { public abstract void Perform(); } class DanceRobot : Robot { public override void Perform() { Console.WriteLine("Dance"); } } abstract class Decorator : Robot { protected Robot m_Robot; public Decorator(Robot robot) { m_Robot = robot; } public override void Perform() { if (m_Robot == null) { return; } m_Robot.Perform(); } } class JumpDecorator : Decorator { public JumpDecorator(Robot robot) : base(robot) { } public override void Perform() { base.Perform(); Console.WriteLine("Jump"); } } class SingDecorator : Decorator { public SingDecorator(Robot robot) : base(robot) { } public override void Perform() { base.Perform(); Console.WriteLine("Sing"); } } } }
裝飾者模式修改版:
using System; using System.Collections.Generic; namespace TestCS { class Program { static void Main(string[] args) { IRobot robot = new DanceRobot(); robot.Perform(); robot = new JumpDecorator(robot); robot.Perform(); robot = new SingDecorator(robot); robot.Perform(); Console.ReadKey(); } interface IRobot { void Perform(); } class DanceRobot : IRobot { public void Perform() { Console.WriteLine("Dance"); } } abstract class Decorator : IRobot { protected IRobot m_Robot; public Decorator(IRobot robot) { m_Robot = robot; } public virtual void Perform() { if (m_Robot == null) { return; } m_Robot.Perform(); } } class JumpDecorator : Decorator { public JumpDecorator(IRobot robot) : base(robot) { } public override void Perform() { base.Perform(); Console.WriteLine("Jump"); } } class SingDecorator : Decorator { public SingDecorator(IRobot robot) : base(robot) { } public override void Perform() { base.Perform(); Console.WriteLine("Sing"); } } } }