标签:现在 sicp ever for 音乐播放 res col HERE imp
原始定义: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(); } }
标签:现在 sicp ever for 音乐播放 res col HERE imp
原文地址:https://www.cnblogs.com/o-andy-o/p/10311958.html