設計模式之單一職責原則

一.單一職責(Single Responsibility Principle,簡稱SRP ): 一個類只負責一項職責

原始定義:There should never be more than one reason for a class to change。ide

官方翻譯:應該有且僅有一個緣由引發類的變動。簡單點說,一個類,最好只負責一件事,只有一個引發它變化的緣由。spa

 

錯誤示範:翻譯

public interface IPhotograph {
    void photograph();
}

public interface IPlayMusic {
    void playMusic();
}
//一個類負責兩個功能
public class MobilePhone implements IPhotograph, IPlayMusic {

    @Override
    public void playMusic() {
        System.out.println("play music");
    }

    @Override
    public void photograph() {
        System.out.println("take photo");
    }

}

public class SRP {
    //拍照和播放音樂兩個當中的任何一個功能的改動都要修改手機類,由於如今的手機既負責拍照又負責播放音樂
    public static void main(String[] args) {
        MobilePhone phone = new MobilePhone();
        IPhotograph photographer = phone;//是照相機
        IPlayMusic player = phone;//是音樂播放器
        photographer.photograph();
        player.playMusic();
    }
}

 

正確作法:code

public interface IPhotograph {
    void photograph();
}

public interface IPlayMusic {
    void playMusic();
}
//一個類負責一個功能
public class MusicPlayer implements IPlayMusic{
    @Override
    public void playMusic() {
        System.out.println("play music");
    }

}

//一個類負責一個功能
public class Carmera implements IPhotograph {
    @Override
    public void photograph() {
        System.out.println("take photo");
    }

}

public class SRP {
    //拍照和播放音樂兩個類各司其職
    public static void main(String[] args) {
        IPhotograph photographer = new Carmera();//是照相機
        IPlayMusic player = new MusicPlayer();//是音樂播放器
        photographer.photograph();
        player.playMusic();
    }
}
相關文章
相關標籤/搜索