设计模式-桥接模式

发布时间:2020-07-15 11:16:45 作者:全嗲吉祥
来源:网络 阅读:305
//职责
abstract class Command
    {
        public abstract int Run<T>(T t);
    }
    class Add : Command
    {
        public override int Run<T>(T t)
        {
            Console.WriteLine("add{0}",t.ToString());
            return 0;
        }
    }
    class Update : Command
    {
        public override int Run<T>(T t)
        {
            Console.WriteLine("update{0}", t.ToString());
            return 0;
        }
    }
    class Delete : Command
    {
        public override int Run<T>(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。

推荐阅读:
  1. 桥接模式
  2. Java描述设计模式(08):桥接模式

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

设计模式 桥接模式

上一篇:用Python如何实现将某一列设置为str类型

下一篇:canvas原生如何实现前端网页移动端签名

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》