Read Design Patterns - adapter mode

Adapter mode

      If you say that we have to develop a new class, but now there is a ready-class functions and we have to develop a new class of similar, but the class name of the class ready not what I want,

      We want the method name method is not what we want (incompatible interfaces), how to do?

     1, class Adapter pattern: inherit an existing class, to achieve the target interface!

      Inherit an existing class, the class of methods can be used, even if the method name of the method is not what we want, then create a method of our own, calling it (the name of the function in the same manner different) ways be established in this method.

      Adapter model class at the time of use, that does not need to pass parameters when creating the adapter class object.

     Note: when we write an adapter class, the class name will usually be written as Adapter, it is merely educational use, in actual use, for example, we want to create a Circle class, while an existing SpecialCircle, adapter class name directly is Circle, inheritance SpecialCircle, realize Shape, not the adapter class is the class name had adapter.

   2, the adapter mode object: not inherit an existing class, but the existing instance of the class as a member variable of the class adapter.

       Then we have to define the method of process (interface), the function call corresponding to the example in the method. This will only need to inherit the target class or implement the target interface, no need to inherit the existing classes.

       Key: We said before the class structural model is static, structural model of the object is dynamic. From then on it is manifested, because we are the example of an existing class as a member variable, then of course you have to write a constructor to the member variable assignment, the constructor is that we will fit into an existing class destination interface way, then we can spread into the parameters passed subclasses of existing classes, that is the object of the adapter pattern can be an existing class and its subclasses are adapted to the target interface

      This is the structural model of dynamic objects reflect .

      The benefits of the CARP (polymerized composition multiplexing principle) and an adapter object model, we should try to use the adapter mode object.

 

 

     

Guess you like

Origin blog.csdn.net/shen19960603/article/details/90601057