设计模式之桥接模式

桥接模式

  1. 桥接模式结构图:

  2. 示例代码:

    // 桥接角色Message接口
    public interface Message {
        void sendMessage(String message, String toUser);
    }
    
    // 具体Message角色Email
    public class EmailMessage implements Message{
        @Override
        public void sendMessage(String message, String toUser) {
            System.out.println("发送Email消息:" + message + "给" + toUser);
        }
    }
    
    // 具体Message角色SMS
    public class SmsMessage implements Message{
        @Override
        public void sendMessage(String message, String toUser) {
            System.out.println("发送Sms短消息:" + message + "给" + toUser);
        }
    }
    
    // 桥接抽象角色AbstractMessage
    public abstract class AbstractMessage {
    
        protected Message message;
    
        public AbstractMessage(Message message) {
            this.message = message;
        }
    
        public abstract void sendMessage(String msg, String toUser) ;
    }
    
    // 普通消息角色
    public class NormalMessage extends AbstractMessage{
        public NormalMessage(Message message) {
            super(message);
        }
    
        @Override
        public void sendMessage(String msg, String toUser) {
            msg = "[普通]" + msg;
            this.message.sendMessage(msg, toUser);
        }
    }
    
    // 紧急消息角色
    public class UrgencyMessage extends AbstractMessage{
        public UrgencyMessage(Message message) {
            super(message);
        }
    
        @Override
        public void sendMessage(String msg, String toUser) {
            msg = "[加急]" + msg;
            this.message.sendMessage(msg, toUser);
        }
    }
    
    // 测试类
    public class BridgeTest {
    
        public static void main(String[] args) {
            NormalMessage normalMessage = new NormalMessage(new EmailMessage());
            normalMessage.sendMessage("今天忙不忙?", "小安");
            UrgencyMessage urgencyMessage = new UrgencyMessage(new SmsMessage());
            urgencyMessage.sendMessage("能不能多聊会?", "小安");
        }
    }
    
    
  3. 总结:

    优点:分离了抽象部分及具体实现部分,提高了系统的扩展性,符合开闭原则;

    缺点:增加了系统的理解与设计难度,需要正确的识别系统中两个独立变化的维度.

posted @ 2021-04-24 23:54  justKen  阅读(62)  评论(0编辑  收藏  举报