找出应用中的可能变化之处,将他们独立出来,将其他不变化的部分放在一起
多用组合,少用继承
面向接口编程,而不是面向实现编程
假设要出门旅行,考虑创建一系列交通工具来供调用
首先考虑不同处:
public interface IFlyBehavior
{
void fly();
}
public interface IPriceBehavior
{
void price();
}
然后是这几种不同分别有几种情况:
public class CanFly implements IFlyBehavior
{
@Override
public void fly()
{
System.out.println("i can fly");
}
}
public class CannotFly implements IFlyBehavior
{
@Override
public void fly()
{
System.out.println("i can't fly");
}
}
public class HighPrice implements IPriceBehavior
{
@Override
public void price()
{
System.out.println("my price high");
}
}
public class MedPrice implements IPriceBehavior
{
@Override
public void price()
{
System.out.println("my price mediate");
}
}
public class LowPrice implements IPriceBehavior
{
@Override
public void price()
{
System.out.println("my price low");
}
}
交通工具的模板,包含其共同之处
public abstract class Vehicle
{
protected IFlyBehavior fly;
protected IPriceBehavior price;
public void performFly()
{
fly.fly();
}
public void perPrice()
{
price.price();
}
public void run()
{
System.out.println("i can run");
}
public abstract void select();
}
那么,就可以分别创建汽车,火车和飞机等:
public class Bus extends Vehicle
{
public Bus()
{
fly = new CannotFly();
price = new MedPrice();
}
@Override
public void select()
{
fly.fly();
price.price();
}
}
public class Train extends Vehicle
{
public Train()
{
fly = new CannotFly();
price = new LowPrice();
}
@Override
public void select()
{
fly.fly();
price.price();
}
}
public class Plane extends Vehicle
{
public Plane()
{
fly = new CanFly();
price = new HighPrice();
}
@Override
public void select()
{
fly.fly();
price.price();
}
}