码迷,mamicode.com
首页 > 其他好文 > 详细

23种设计模式之桥接模式代码实例

时间:2017-11-24 21:42:59      阅读:97      评论:0      收藏:0      [点我收藏+]

标签:div   extend   ble   system   end   string   sub   xtend   rac   

桥接模式就是把事物与其具体的实现相分离,抽象化与实现化解耦。

    public interface Sourceable {  
        public void method();  
    }  
    public class SourceSub1 implements Sourceable {  
      
        @Override  
        public void method() {  
            System.out.println("this is the first sub!");  
        }  
    }  
    public class SourceSub2 implements Sourceable {  
      
        @Override  
        public void method() {  
            System.out.println("this is the second sub!");  
        }  
    }  
    public abstract class Bridge {  
        private Sourceable source;  
      
        public void method(){  
            source.method();  
        }  
          
        public Sourceable getSource() {  
            return source;  
        }  
      
        public void setSource(Sourceable source) {  
            this.source = source;  
        }  
    }  
    public class MyBridge extends Bridge {  
        public void method(){  
            getSource().method();  
        }  
    }  

测试类:

    public class BridgeTest {  
          
        public static void main(String[] args) {  
              
            Bridge bridge = new MyBridge();  
              
            /*调用第一个对象*/  
            Sourceable source1 = new SourceSub1();  
            bridge.setSource(source1);  
            bridge.method();  
              
            /*调用第二个对象*/  
            Sourceable source2 = new SourceSub2();  
            bridge.setSource(source2);  
            bridge.method();  
        }  
    }  

输出:

this is the first sub!
this is the second sub!

 

23种设计模式之桥接模式代码实例

标签:div   extend   ble   system   end   string   sub   xtend   rac   

原文地址:http://www.cnblogs.com/longhaolove/p/7892114.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!