设计模式之单一职责原则

一.单一职责(Single Responsibility Principle,简称SRP ): 一个类只负责一项职责

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

官方翻译:应该有且仅有一个原因引起类的变更。简单点说,一个类,最好只负责一件事,只有一个引起它变化的原因。

 

错误示范:

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();
    }
}

 

正确做法:

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();
    }
}

 

posted on 2019-01-23 22:49  lovebeauty  阅读(335)  评论(0编辑  收藏  举报

导航