设计模式之Programming to an Interface, not anImplementation 程序指向接口,而不是实现


Class inheritance is basically just a mechanism for extending an application's functionality by reusing functionality in parent classes. It lets you define a new kind of object rapidly in terms of an old one. It lets you get new implementations almost for free, inheriting most of what you need from existing classes.

类的继承只是通过重用父类里的函数为延长应用函数提供了基础的机制。它会让你更快速的利用旧有的对象来快速定义新的对象。它让你几乎是很轻的得到新的实现。继承在多数情况下是从存在的类中得到你想要的。

However, implementation reuse is only half the story. Inheritance's ability to define families of objects with identical interfaces (usually by inheriting from an abstract class) is also important. Why?Because polymorphism depends on it.

然而,实现的重用只是这个故事的一半。用相同的接口定义家族式的对象的继承能力很重要。(通常通过抽象类来实现继承)为什么?因为多态依赖与它。

When inheritance is used carefully (some will say properly), all classes derived from an abstract class will share its interface. This implies that a subclass merely adds or overrides operations and does not hide operations of the parent class. All subclasses can then respond tothe requests in the interface of this abstract class, making them all subtypes of the abstract class.

当继承被谨慎的使用时(有的地方会说“恰当”),所有从抽象类衍生出来的类会共享这些接口。这纯粹是子类的增加或覆盖运算,而不是隐藏父类的运算。

There are two benefits to manipulating objects solely in terms of the interface defined by abstract classes:

1. Clients remain unaware of the specific types of objects they use, as long as the objects adhere to the interface that clients expect.

2. Clients remain unaware of the classesthat implement these objects. Clients only know about the abstract class(es)defining the interface.

根据抽象类定义的接口来操作对象有两个独一无二的好处

(1)   客户不会意识到他们所用的特殊类型的对象,像客户期待的那样只要对象遵循接口即可。

(2)   客户不会意识到实现对象的类。客户仅仅只是知道定义这个接口的抽象类。

This so greatly reduces implementation dependencies between subsystems that it leads to the following principle of reusable object-oriented design: Program to an interface, not an implementation.

这也大量减少了子系统之间实现的依赖,它导致了面向对象设计中的一下原则:程序指向接口,而不是实现。

Don't declare variables to be instances of particular concrete classes. Instead, commit only to an interface defined by an abstract class. You will find this to be a common theme of the design patterns in this book.

不声明变量是特定的具体类的实现。取而代之的是,通过抽象类定义的接口来实现调配。在这本书里,你会发现这是普遍的主题。

You have to instantiate concrete classes(that is, specify a particular implementation) somewhere in your system,of course, and the creational patterns(Abstract Factory (99), Builder (110),Factory Method (121), Prototype (133),and Singleton (144) let you do just that.By abstracting the process of object creation, these patterns give you differentways to associate  an interface with

its implementation transparently at instantiation. Creational patterns ensure that your system is written in terms of interfaces, not implementations.

在系统的某些地方,你不得不去实例化具体的类(这些是特殊的实现)。

当然,创建模式和单体会让你做这些。通过抽象对象创建的进程,在实例化的过程中,这些模式会给你提供不同的易于觉察的方法来联系这些接口。创建模式

会保证在你的系统中的接口的安全,而不是实现。

原文地址:https://www.cnblogs.com/james1207/p/3260343.html