博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
常识# 统一访问原则 (uniform acces principle)
阅读量:4463 次
发布时间:2019-06-08

本文共 1585 字,大约阅读时间需要 5 分钟。

The Uniform Access Principle was put forth by Bertrand Meyer. It states "All services offered by a module should be available through a uniform notation, which does not betray whether they are implemented through storage or through computation." This principle applies generally to object-oriented programming languages. In simpler form, it states that there should be no difference between working with an attribute, precomputed property, or method/query.

上文是wiki里对统一访问原则的描述,用《scala编程》一书中的说法就是“客户代码不应由属性是通过字段实现还是方法实现而受到影响”。这句话到底什么意思呢?代码说话

elem.width

上面这种表达方式有两种实现形式,当改成任意的另外一种时,都不会改变当前代码的用法。(当然对某些语言是行不通的)

class Elem{  val width = 1}
class Elem{  def width:Int = 1}

 

 

另附wiki上用python语言写的例子

egg = Egg( 4, "White")egg.color = "Green"print egg.weight, egg.color, egg.quack()  # prints: 4 Green quack

字段实现

class Egg(object):   def __init__(self, weight, color):      self.weight = weight      self.color = color   def quack(self):      return "quack"

方法实现

class Egg(object):    def __init__(self, weight, color):      self.__weight = toGrams(weight)      self.__color = toRGB(color)     def setColor(self, colorname):      self.__color = toRGB(colorname)     def getColor(self):      return toColorName(self.__color)     color = property(getColor, setColor, doc="Color of the Egg")     def setWeight(self, weightOz);       self.__weight = 29.3*weightOz     def getWeight(self):       return self.__weight/29.3;     weight = property(setWeight, getWeight, doc="Weight in Ounces")     def quack(self):       return "quack"

 

 

 

转载于:https://www.cnblogs.com/mattmonkey/archive/2012/12/11/2813366.html

你可能感兴趣的文章
Sharepoint Solution Gallery Active Solution时激活按钮灰色不可用的解决方法
查看>>
教你50招提升ASP.NET性能(二十二):利用.NET 4.5异步结构
查看>>
lua连续随机数
查看>>
checkstyle使用介绍
查看>>
会了这十种Python优雅的写法,让你工作效率翻十倍,一人顶十人用!
查看>>
二维码图片生成
查看>>
在做操作系统实验的一些疑问
查看>>
Log4J日志配置详解
查看>>
NameNode 与 SecondaryNameNode 的工作机制
查看>>
Code obfuscation
查看>>
大厂资深面试官 带你破解Android高级面试
查看>>
node.js系列(实例):原生node.js实现接收前台post请求提交数据
查看>>
SignalR主动通知订阅者示例
查看>>
golang的表格驱动测试
查看>>
用python实现矩阵转置
查看>>
linux 小技巧(磁盘空间搜索)
查看>>
iOS开发——捕获崩溃信息
查看>>
(for 循环)编程找出四位整数 abcd 中满足 (ab+cd)(ab+cd)=abcd 的数
查看>>
tomcat使用spring-loaded实现应用热部署
查看>>
boost1.53中的lock-free
查看>>