Decouple an abstraction from its implementation so that the two can vary independently.(将抽象和实现解耦,使得倆者可以独立的变化)
public abstract class Product { public abstract void beProducted(); public abstract void beSelled(); }
公司抽象
public abstract class Corp { private Product product; public Corp(Product _product){ this.product=_product; } public void makeMoney(){ this.product.beProducted(); this.product.beSelled(); } }
房子也是产品不是吗?
public class House extends Product { @Override public void beProducted() { System.out.println("生产出的房子是这样的..."); } @Override public void beSelled() { System.out.println("生产出的房子卖出去了...."); } }
public class IPod extends Product { @Override public void beProducted() { System.out.println("生产出的ipod是这样的"); } @Override public void beSelled() { System.out.println("生产的IPod卖出去了"); } }
public class HouseCorp extends Corp { public HouseCorp(House _house) { super(_house); } @Override public void makeMoney() { super.makeMoney(); System.out.println("房地产公司赚大钱了"); } }
public class ShanZhaiCorp extends Corp { public ShanZhaiCorp(Product _product) { super(_product); } @Override public void makeMoney() { super.makeMoney(); System.out.println("我是山寨,我赚钱呀"); } }
场景测试
public static void main(String[] args) { System.out.println("房地产公司是这样运行的"); House house=new House(); HouseCorp houseCorp=new HouseCorp(house); houseCorp.makeMoney(); System.out.println(); System.out.println("山寨公司是这样运行的"); ShanZhaiCorp shanZhaiCorp=new ShanZhaiCorp(new IPod()); shanZhaiCorp.makeMoney(); }
瞧瞧人家山寨公司,什么东西流行就生产什么,反正价格低,质量嘛也有那么一点点保证。
我是菜鸟,我在路上。