Chapter 5 的第二段
We’ve already seen how classes help. All the methods in a class are automatically accessible to instances of that class. But there are other, more general types of sharing that we want to do. Maybe we’re dealing with an application that ships goods. Many forms of shipping are available, but all forms share some basic functionality (weight calculation, perhaps). We don’t want to duplicate the code that implements this functionality across the implementation of each shipping type. Or maybe we have a more generic capability that we want to inject into a number of different classes. For example, an online store may need the ability to calculate sales tax for carts, orders, quotes, and so on. Again, we don’t want to duplicate the sales tax code in each of these places.
我们已经知晓了类的功效。一个类的所有方法都可在其创建实例中灵活地调用。除此之外,我们更期望有更多的常用类型能够共享使用。假设我们要处理一个关于货轮运输的程序。有很多地运送形式可以选择,但某些基本方法对于所有的形式都是可共用的,比如重量计算。针对每一个运送类型,我们不希望照搬重复的代码,用实现每个对应类型的接口的方式完成这个功能。或者说,也许有这样一个更通用的方法,可以按我们的意愿被注入到不同的类中。例如,在线商店就需要为购物车、订单和价格等计算消费税。同样地,我们不希望在每个需要计税的地方都要复制这些代码。
第一次翻译技术文章,有很多不准确的地方,请各路高人指教,如能附上您的专业版,不胜感激!