桥接模式:将抽象部分与它的实现部分分离,使它们都可以独立的变化。
并不是说,让抽象类与其派生类分离,因为这没有任何意义。实现指的是抽象类和它的派生类用来实现自己的对象。
实现系统可能有多角度分类,每一种分类都有可能变化,那么就把这种多角度分离出来让它们独立变化,减少它们之间的耦合。
当发现需要多角度去分类实现对象,只用继承会造成大量的类增加,要考虑使用桥接模式。
接口作为桥,接口实现类实现相应方法,抽象类作为具体实现,抽象类有接口对象属性,抽象类子类实现抽象方法,在方法中去调用接口的方法。
/**
* 手机软件接口,作为桥
*/
public interface Soft {
void run(); //运行软件的方法
}
/**
* 游戏软件
*/
public class SoftGame implements Soft{
@Override
public void run() {
System.out.println("运行手机游戏");
}
}
/**
* 音乐软件
*/
public class SoftMusic implements Soft{
@Override
public void run() {
System.out.println("运行手机音乐软件");
}
}
/**
* 抽象手机品牌
*/
public abstract class Brand {
private Soft soft;
public Soft getSoft() {
return soft;
}
public void setSoft(Soft soft) {
this.soft = soft;
}
public abstract void run(); //运行
}
/**
* M品牌手机
*/
public class BrandM extends Brand{
@Override
public void run() {
System.out.println("M手机运行中···");
this.getSoft().run();
}
}
/**
* N品牌手机
*/
public class BrandN extends Brand {
@Override
public void run() {
System.out.println("N手机运行中···");
this.getSoft().run();
}
}
public class Main {
public static void main(String[] args) {
Brand m = new BrandM();
m.setSoft(new SoftGame());
m.run();
}
}