定义:将抽象部分与它的实现部分分离,使它们都可以独立地变化。
结构图:
public abstract class HandSetBrand {
protected HandSetSoft soft;
public HandSetSoft getSoft() {
return soft;
}
public void setSoft(HandSetSoft soft) {
this.soft = soft;
}
public abstract void Run();
}
interface HandSetSoft {
void Run();
}
public class HandsetGame implements HandSetSoft{
@Override
public void Run() {
System.out.println("运行手机游戏");
}
}
public class HandsetAddressList implements HandSetSoft{
@Override
public void Run() {
System.out.println("运行手机通讯录");
}
}
<pre name="code" class="java">public abstract class Han<pre name="code" class="java">public class Client {
public static void main(String[] args) {
HandSetBrand hsb;
hsb = new HandSetBrandN();
hsb.setSoft(new HandsetGame());
hsb.Run();
hsb.setSoft(new HandsetAddressList());
hsb.Run();
hsb = new HandSetBrandN();
hsb.setSoft(new HandsetGame());
hsb.Run();
hsb.setSoft(new HandsetAddressList());
hsb.Run();
}
}
dSetBrand {protected HandSetSoft soft;public HandSetSoft getSoft() {return soft;}public void setSoft(HandSetSoft soft) {this.soft = soft;}public abstract void Run();}
public class HandSetBrandB extends HandSetBrand{@Overridepublic void Run() {soft.Run();}}public class HandSetBrandN extends HandSetBrand{@Overridepublic void Run() {soft.Run();}} 实现系统可能有多角度分类,每一钟分类都有可能变化,那么就把这种多角度分离出来让它们独立变化,减少它们之间的耦合。