2021-05-12 14:32:11
Spring自動化裝配bean
2020-06-16 17:12:59
1. 場景
用CD(Compact disc)和CD播放器(CDPlayer)闡述DI(依賴注入)。如果不將CD插入(注入)到CDPlayer中,那麼CDPlayer其實沒有太大的用處,所以,可以這樣說:CDPlayer依賴於CD才能完成它的使命。
2. 架構圖示
3. 程式碼
介面: CompactDisc.java
package soundsystem; public interface CompactDisc { void play(); }
介面: MediaPlayer.java
package soundsystem; public interface MediaPlayer { void play(); }
SgtPeppers.java
package soundsystem; import org.springframework.stereotype.Component; @Component public class SgtPeppers implements CompactDisc { private String title = "Sgt. Pepper's Lonely Hearts Club Band"; private String artist = "The Beatles"; @Override public void play() { System.out.println("Playing " + title + " by " + artist); } }
相關文章