桥接模式定义:将抽象和实现解耦,使得两者可以独立地变化。
优点:
1、抽象和实现分离。
桥接模式是为了解决继承的缺点而提出的设计模式,这种模式下,实现可以不受抽象的约束,不用再绑定在一个固定的抽象层次上。
2、优秀的扩展能力。
3、实现细节对客户透明。
类图如下:
实现代码如下:
抽象化角色AbstractUser :
package com.designpatterns.bridge; public abstract class AbstractUser { private Implements imp; public AbstractUser(Implements imp) { this.imp = imp; } public void request(){ this.imp.doString(); } public Implements getImp() { return imp; } }房地产公司实现类:
package com.designpatterns.bridge; public class HouseUser extends AbstractUser { public HouseUser(Implements imp) { super(imp); } @Override public void request(){ super.request(); super.getImp().doAnyString(); } }
package com.designpatterns.bridge; public class ShanZhaiUser extends AbstractUser { public ShanZhaiUser(Implements imp) { super(imp); } @Override public void request(){ super.request(); super.getImp().doAnyString(); } }
抽象的实现化角色:
package com.designpatterns.bridge; public interface Implements { public void doString(); public abstract void doAnyString(); }
package com.designpatterns.bridge; public class HouseImpImplements implements Implements { public HouseImpImplements() { // TODO Auto-generated constructor stub } @Override public void doString() { System.out.println("I come from HousrImpImplemnts"); } @Override public void doAnyString() { System.out.println("I can make money"); } }
package com.designpatterns.bridge; public class ShanZhaiImpImplements implements Implements { public ShanZhaiImpImplements() { // TODO Auto-generated constructor stub } @Override public void doString() { System.out.println("I come from ShanZhaiImpImplements."); } @Override public void doAnyString() { System.out.println("I can make money from ShanZhai."); } }
package com.designpatterns.bridge; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Type; import java.util.ArrayList; public class Client { public Client() { } public static void main(String[] args) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException, ClassNotFoundException { ArrayList<AbstractUser> list = new ArrayList<AbstractUser>(); Implements Himp= new HouseImpImplements(); AbstractUser HU= new HouseUser(Himp); Implements SZimp= new ShanZhaiImpImplements(); AbstractUser SZU= new ShanZhaiUser(SZimp); list.add(SZU); list.add(HU); for (AbstractUser abstractUser : list) { System.out.println("this is :" +abstractUser.getClass().getName()); abstractUser.request(); System.out.println("-----------------------"); } } }
参考资料:
设计模式之禅
备注:
转载请注明出处
http://blog.csdn.net/wsyw126/article/details/51336078
WSYW126