Six design principles-Interface Isolation principle "Interface segregation Principle"

Source: Internet
Author: User

Disclaimer: The content of this article is from the network of books collated, not original.

Defined
    • The first type of definition:

      Clients should not being forced to depend upon interfaces that they don ' t use.
      The client should not rely on interfaces it does not need.

    • The second definition:

      The dependency of one class to another one should depend on the smallest possible interface.
      The dependencies between classes should be based on the smallest interface.

      Two definitions, such as a withdrawal, are just two different descriptions of a thing.
      We can summarize these two definitions into one sentence: Create a single interface and don't build a bloated, bulky interface. Another popular point: the interface as far as possible refinement, and the interface of the method as little as possible. See here you may wonder, is this not the same as the single principle of responsibility? Wrong, the principle of interface isolation and the definition of a single duty is not the same, a single responsibility requires a single class and interface responsibilities, focus on the responsibility, there is no need to reduce the interface method, such as a duty may contain 10 methods, these 10 methods are placed in an interface, and provided to multiple modules access, Each module is accessed in accordance with the prescribed permissions, the method is not used outside the system through the document constraints do not access, in accordance with the principle of single responsibility is allowed, according to the principle of interface isolation is not allowed, because it requires "to use more than a dedicated interface," The special interface refers to what? Refers to the interface provided to multiple modules, provided to several modules should have several interfaces, rather than build a huge bloated interface, all the modules can be accessed since.

Beauty and the example of a star scout

Let's define what a beauty is: 1. Look good, 2. Be slim, 3. Have temperament. We use class diagram class to reflect the process of Star Scout looking for beauty:

Definition of beauty:

publicinterface IPettyGirl {    //要有姣好的面孔    publicvoidgoodLooking();    //要有好身材    publicvoidniceFigure();    //要有气质    publicvoidgreatTemperament();}

Beauty's implementation class:

 Public  class pettygirl implements ipettygirl {    PrivateString name;//Beauty has a name     Public Pettygirl(String _name) { This. name=_name; }//Beautiful face     Public void goodlooking() {System.out.println ( This. Name +"---a beautiful face!"); }//temperament is better     Public void greattemperament() {System.out.println ( This. Name +"---very nice."); }//Good figure     Public void nicefigure() {System.out.println ( This. Name +"---was great!"); }}

Then we look at the Abstractsearcher class, this class refers to the star Scout industry, the code is as follows:

publicabstractclass AbstractSearcher {    protected IPettyGirl pettyGirl;    publicAbstractSearcher(IPettyGirl _pettyGirl){        this.pettyGirl = _pettyGirl;    }    //搜索美女,列出美女信息    publicabstractvoidshow();}

Star exploration find beauty, print out the information of beauty, the code is as follows:

 Public  class Searcher extends abstractsearcher{     Public Searcher(Ipettygirl _pettygirl) {Super(_pettygirl); }//Show the beauty information     Public void Show() {System.out.println ("--------beauty information is as follows:---------------");//Display face        Super. pettygirl.goodlooking ();//Show Body        Super. Pettygirl.nicefigure ();//Display temperament        Super. Pettygirl.greattemperament (); }}

Two characters in the scene the beauty and the Scout are all done, and we'll write a scene class that shows us the process:

publicclass Client {    //搜索并展示美女信息    publicstaticvoidmain(String[] args) {        //定义一个美女        new PettyGirl("嫣嫣");        new Searcher(yanYan);        searcher.show();    }}

The results of the operation are as follows:

--------The beauty information is as follows: ---------------The wee---The face is very beautiful!The wee---very good figure!The wee---very good temperament!

Star Scout to find the beauty of the program we have developed, we have to think about this program has no problem, think about ipettygirl This interface, this interface is the best design.

Our aesthetic views are changing, and the definition of beauty is changing. More than 1000 years ago in the Tang Dynasty, if living in the modern age is not ashamed to die, why? Oh, fat! But fat does not affect her in China's four beautiful ranks, indicating that the aesthetic and now there is a difference, of course, with the development of the Times our aesthetic is also changing, right now, you find a girl, the face is not good, the body is general, but temperament very well, most people will be such a girl called Beauty, Aesthetic quality has been improved, but we have the interface defines the beauty must be three have yes, maybe you have to say, I re-expand a beauty class, only realize the Greattemperament method two other methods set empty, what do not write, you can do it? Smart, but it won't work! Why is it? Star Scout Abstractsearcher relies on the Ipettygirl interface, it has three methods, you only implemented two methods, the method is not to change the star Scout? Our above program print out of two less information, but also let the star Scout How to identify is not beautiful? Well, we found our interface Ipettygirl interface design is flawed, too large, accommodating a number of variable factors, according to the interface isolation principle, the Scout abstractsearcher should rely on and have some of the characteristics of the girls, and we have these characteristics are encapsulated together, Put it in a connector, the package transitions! The problem is found, we re-modify the class diagram:

The original Ipettygirl interface split into two interfaces, one is beautiful beauty igoodbodygirl, this kind of beauty is characterized by a very good face and body, superior, but no aesthetic quality, such as spitting, Export is Kao,cao and the like, the level of education is relatively low, the other is the beauty of temperament Igreattemperamentgirl, talk and culture are very high. We split from a more bloated interface into two dedicated interfaces, flexibility, and increased maintainability, regardless of the beauty of the future is to be beautiful or beautiful beauty can easily through the pettygirl definition. Let's look at the two types of beauty interfaces first:

publicinterface IGoodBodyGirl {    //要有姣好的面孔    publicvoidgoodLooking();    //要有好身材    publicvoidniceFigure();}publicinterface IGreatTemperamentGirl {    //要有气质    publicvoidgreatTemperament();}

The implementation class does not change, just implement the class two interfaces, the code is as follows:

 Public  class pettygirl implements igoodbodygirl,igreattemperamentgirl {     PrivateString name;//Beauty has a name     Public Pettygirl(String _name) { This. name=_name; }//Beautiful face     Public void goodlooking() {System.out.println ( This. Name +"---a beautiful face!"); }//temperament is better     Public void greattemperament() {System.out.println ( This. Name +"---very nice."); }//Good figure     Public void nicefigure() {System.out.println ( This. Name +"---was great!"); }}

After such a transformation, regardless of the future is to temperament beauty or shape beauty, can maintain the stability of the interface. Of course, you may have to say, the future may be the aesthetic point of change, only the face is beautiful, that the Igoodbody interface is to be modified Ah, it is, but there is a limit to the design, can not be unlimited consideration of the future changes, otherwise it will fall into the mire of design and can not extricate themselves.

The principle of changing a bloated interface to two independent interfaces depends on the principle of interface isolation, which makes Abstractsearcher dependent on two dedicated interfaces more flexible than relying on a single integrated interface. Interface is the contract we provide when we design, we can prevent the proliferation of future changes and improve the flexibility and maintainability of the system by dispersing and defining multiple interfaces.

The interface isolation principle contains four layers of meaning
  1. The interface should be as small as possible . This is the core definition of the interface isolation principle, there is no bloated interface (Fat Interface), but "small" is limited, first of all, can not violate the principle of single responsibility, what does it mean? We refer to an example of an IPhone in the single responsibility principle, where we use a single principle of responsibility to decompose the methods in an interface into two interfaces, as shown in the following example:

    We think about whether the Iconnectmanager interface can continue to split up, hang the phone there are two ways: one is the normal phone hangs, one is the phone suddenly no power, the communication is of course broken, the two ways of processing should be different, for what? Normal hanging phone, the other side to accept the hanging signal, billing system also stopped billing, the phone did not power this way is different, it is lost signal, relay server check to, and then notify the billing system to stop billing, otherwise your costs are not going crazy growth?! Think about here, we are not going to do the Iconnectmanager interface into two, one is responsible for the connection, an interface is responsible for hanging the phone? Is that what you're doing? Wait, let us think again, if split, it does not conform to the principle of single responsibility, because from the business to establish and close the communication is the smallest business units, and then subdivide the business or the agreement (other business logic) disassembly, think of a call to care about the 3G protocol, To consider relay server and so on, how can this phone be done? From the business level, such a design is a failed design. A principle to dismantle, you do not dismantle the principle, how to do? Good, * When splitting an interface according to the principle of interface isolation, you must first satisfy the principle of single responsibility .

  2. The interface should be high-cohesion . What is high cohesion? High cohesion is to improve the interface, class, module processing capacity, reduce external interaction, such as a person, you tell subordinates "to Obama's office to steal a XX file", and then heard subordinates on the firm tone answer you "good, guaranteed to complete!" "And then one months later really put the XX file to your desk, this does not say any conditions, the immediate completion of the task is the performance of high cohesion." The specific to the interface isolation principle is to require in the interface as little as possible to publish public methods, interface is a commitment to the external, the less commitment to the development of the system is more favorable, the risk of change will be less, but also help reduce costs.

  3. Customized Services。 There is bound to be a coupling between the modules within a system or system, the interfaces that are connected to each other (not necessarily the Interface defined in Java, or a class or a simple data exchange), and we need to design a service for each visitor (and client), what is a custom service? You go to the mall to buy clothes, to find the size of their own body of clothing has become, basically will not be too big, may be the former loose after the tight, sleepless night sleep and the like is not appropriate, but at least a dress, can wear. What would it look like if you made a dress in a tailor's shop? The tailor will help you to measure your waistline, bust, shoulder width and so on, and then make a dress that is sure to suit your body, and that's the custom service that provides excellent service to an individual individually. When we do system design, we also need to consider the definition between the system or the module to use custom services, the use of custom services must have a requirement is: only provide the method that the visitor needs, what does that mean? We give an example to illustrate, for example, we have done a library management system, which has a query interface, convenient for administrators to query the book, its class diagram is as follows:

    In the interface to define a number of methods, respectively, according to the author, title, publishing house, classification query, and finally provide a hybrid query method, the program is also written, put into production, and suddenly one day found that the system is very slow, and then began the painful analysis, the final discovery is through the interface of the Complexsearch (map map) method concurrency is too large, causing the application server performance degradation, and then continue to track down to find that these queries are launched from the public network, further analysis, found that the problem: to the public network (public network project is another project development) of the query interface and the interface provided to the management personnel in the system is the same , is the Ibooksearcher interface, but the permissions are different, the System Manager can be queried through this interface to all books, and the public network This method is limited, do not return any value, in the design by verbal constraints, this method is not callable, but because of the public network project group negligence, This method is still published out, although can not return the results, but still caused the performance of the application server is very slow to happen, this is a live interface bloated caused by the performance of the Minister of the case.
    When the problem is found, we refactor the interface: Split the ibooksearcher into two interfaces, such as:

    The implementation class provided to the manager implements Isimplebooksearcher and Icomplexbooksearcher two interfaces simultaneously, the original program does not have any change, and the interface provided to the public network becomes Isimplebooksearcher, Only simple queries are allowed, and services are customized for it alone.

  4. there is a limit to the design of the interface . Interface design granularity is the smaller the system the more flexible, this is indisputable fact, but this brings the complexity of the structure, the development difficulty increases, the maintainability is reduced, this is not a project or product expected to see, all interface design must pay attention to moderate, moderate "degree" how to judge? Judging by experience and common sense!

Several rules for dividing interface granularity
    • an interface serves only one submodule or business logic .
    • the public method in the interface is compressed through the business logic . Interface often to review, as far as possible to make the interface to achieve "flesh", rather than "fat doodle" a lot of methods.
    • has been contaminated with the interface, as far as possible to modify, if the risk of a large change, the use of adapter mode for conversion processing .
    • understand the environment and refuse to follow blindly . Each project or product has a specific environmental factors, although the master is to do so you copy, do not, the environment is different, interface split standards are different. In-depth understanding of the business logic, the best interface design comes from your hand!

The interface isolation principle, like other design principles, takes more time and effort to design and plan, but it gives you the flexibility of design that makes it easy for business people to respond to "unreasonable" demands. The best way to implement the principle of using interface isolation is to have an interface that guarantees absolute compliance with the principle of interface isolation (which may not conform to a single principle of responsibility), but will you use it?! No, unless you're crazy! So how do you use the interface isolation principle correctly? The answer is based on experience and common sense to determine the size of the interface granularity, interface granularity is too small, resulting in a proliferation of interface data, developers choke on the interface of the sea; interface granularity is too large, flexibility is reduced, can not provide customized services to the overall project to bring unpredictable risks.

How to accurately practice the principle of interface isolation? Word: Practice, experience and comprehension!

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Six design principles-Interface Isolation principle "Interface segregation Principle"

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.