本文共 1925 字,大约阅读时间需要 6 分钟。
//职责abstract class Command { public abstract int Run(T t); } class Add : Command { public override int Run (T t) { Console.WriteLine("add{0}",t.ToString()); return 0; } } class Update : Command { public override int Run (T t) { Console.WriteLine("update{0}", t.ToString()); return 0; } } class Delete : Command { public override int Run (T t) { Console.WriteLine("delete{0}", t.ToString()); return 0; } } //实体类 bstract class Entity { protected Command command; public void SetCommand(Command _command) { command = _command; } public abstract int Run(); } class User : Entity { public string name { get; set; } public int age { get; set; } public override int Run() { return command.Run(this); } } class Manager : Entity { public string name { get; set; } public int age { get; set; } public override int Run() { return command.Run(this); } } //前端 static void Main(string[] args) { Command add = new Add(); Command update = new Update(); Command delete = new Delete(); Entity user = new User(); user.SetCommand(add); user.Run(); user.SetCommand(update); user.Run(); user.SetCommand(delete); user.Run(); Console.ReadLine(); }
总结:DEMO不是很适合做桥接模式,但是完全实现了桥接模式。
桥接模式就是把抽象类和他的职责分离,重新把职责整个一个新的抽象,然后把职责注入到抽象类。用到了聚合(合成)复用原则(能用聚合的尽量不要用继承),符合单一,开闭原则。优点:避免了继承类的无线扩大,并且扩展性增强。缺点:对业务理解不到位,可能被错误运用,就像DEMO。转载于:https://blog.51cto.com/5591787/2119636