桥接模式

桥接模式应用场景:

比如在商场买手机,你可以买各种品牌的手机,而各种品牌的手机又很多种促销的礼品可供选择,那么就存在多个维度的变化。

 

public interface Gift {
		public String selectGift();
}

 

 

/**
 * 买手机的时候可以选择什么样的赠品
 * @author nickyzhang
 */
public abstract class AbstarctCellphone {
		protected Gift gift;
		public AbstarctCellphone (Gift gift){
				this.gift =gift;
		}
		
		public abstract void BuyCellphone();
}

 

 

public class CellphoneChain implements Gift{
	public String selectGift() {
			return "手机链";
	}
}

 

 

public class MobilePhonePower implements Gift {
		public String selectGift() {
				return "手机移动电源";
		}
}

 

 

public class GalaxyS4 extends AbstarctCellphone {

		public GalaxyS4(Gift gift) {
				super(gift);
		}

		public void BuyCellphone() {
				System.out.println("I have bought  GalaxyS4 "+super.gift.selectGift());
		}
}

 

 

public class IPhone4S extends AbstarctCellphone {
		public IPhone4S(Gift gift) {
				super(gift);
		}
		public void BuyCellphone() {
				System.out.println("I have bought  IPhone4S "+super.gift.selectGift());
		}
		
}

 

 

public class BridgeTest {
		public static void main(String[] args) {
				//购买三星且选择手机链
				AbstarctCellphone cellPhone1= new GalaxyS4(new CellphoneChain());
				cellPhone1.BuyCellphone();
				//购买苹果且选择移动电源
				AbstarctCellphone cellPhone2 = new IPhone4S(new MobilePhonePower());
				cellPhone2.BuyCellphone();
		}
}

 

你可能感兴趣的:(桥接模式 设计模式)