标签:interface 一个 player auto oss span his void 参考资料
public class DvdPlayMissionImpossible { private MissionImpossibleCd missionImpossibleCd; public DvdPlayMissionImpossible(){ this.missionImpossibleCd = new MissionImpossibleCd(); // 紧耦合 } public void play(){ System.out.println("一台只能看" + missionImpossibleCd.getCompactDiskName() + "的DVD"); } } public class DvdPlayFurious { private FuriousCd furiousCd; public DvdPlayFurious(){ this.furiousCd = new FuriousCd(); // 紧耦合 } public void play(){ System.out.println("一台只能看" + furiousCD.getCompactDiskName() + "的DVD"); } } public class MissionImpossibleCd { public String getCompactDiskName(){ return "碟中谍"; } } public class FuriousCd { public String getCompactDiskName(){ return "速度与激情"; } } // Traditional Way. @Test public void dvdPlayerMissionImpossibleTest(){ DvdPlayMissionImpossible dvdPlayMissionImpossible = new DvdPlayMissionImpossible(); DvdPlayFurious dvdPlayFurious = new DvdPlayFurious(); dvdPlayMissionImpossible.play(); // 一台只能看碟中谍的DVD dvdPlayFurious.play(); // 一台只能看速度与激情的DVD }
public interface CompactDisk { String getCDName(); } @Component public class MissionImpossible implements CompactDisk { @Override public String getCDName() { return "碟中谍"; } } @Component public class Furious implements CompactDisk{ @Override public String getCDName() { return "速度与激情"; } }
public interface MediaPlayer { void play(); } @Component public class DvdPlayer implements MediaPlayer { @Autowired @Qualifier("missionImpossible") private CompactDisk cd; @Override public void play() { System.out.println("一台可以看" + cd.getCDName() + "的DVD"); } } @Component public class VCDPlayer implements MediaPlayer { @Autowired @Qualifier("furious") private CompactDisk cd; @Override public void play() { System.out.println("一台可以看" + cd.getCDName() + "的VCD"); } }
@Autowired DvdPlayer dvdPlayer; @Autowired VCDPlayer vcdPlayer; // DI Way. @Test public void dvdAndVcdPlayerTest(){ dvdPlayer.play(); // 一台可以看碟中谍的DVD vcdPlayer.play(); // 一台可以看速度与激情的VCD }
标签:interface 一个 player auto oss span his void 参考资料
原文地址:https://www.cnblogs.com/YaoFrankie/p/11432938.html