信息专家原则(Information Expert Principle)
(1)问题
给对象分配职责的通用原则是什么?
(2)方案
将职责分配给拥有履行一个职责所必需信息的类,即信息专家。
(3)分析
信息专家原则是面向对象设计的最基本原则。通俗点来讲,就是一个类只做自己应该做的事。在系统设计时,需要将职责分配给具有实现这个职责所需要信息的类。信息专家原则对应于面向对象设计原则中的单一职责原则。
示例:
public class AES {
public string Decrypt(string ciphertext, string salt) {
throw new NotImplementedException();
}
public void Post(string url, string cleartext, Dictionary<string, string> heads) {
throw new NotImplementedException();
}
}
AES解密类,Decrypt方法为解密方法,需要传递密文和盐,这个类中包含了另外一个方法Post以向某个url发送明文数据。
显然Post方法不应该属于AES类,因为职责分配不合理。解密类应专注于解密动作,发送数据的Post方法应该封装在另外一个类中。以下是解决方案:
public class AES {
public string Decrypt(string ciphertext, string salt) {
throw new NotImplementedException();
}
}
public class PostUtil {
public static void Post(string url, string content, Dictionary<string, string> heads) {
throw new NotImplementedException();
}
}
经过简单的改造,AES类变成了AES解密的信息专家,而PostUtil工具类变成了发送数据的信息专家。
扫描二维码关注公众号,回复:
2618385 查看本文章
![](/qrcode.jpg)