What is an interface (intermediate)--the use of interfaces in design mode (ii)

Source: Internet
Author: User

Remember what my software engineering teacher said: It should be designed in a cohesion, low-coupling direction.

At that time, also as a beginner, I do not quite understand the teacher's sentence-since the object-oriented provides us with the concept of "inherit" the high-coupling, then why do we have low-coupling high cohesion? Does the concept of inheritance not be used instead of the process-oriented?

With this question, I consulted my teacher, and he gave me the answer: the interface to separate the separation logic, you can achieve a low-coupling effect.

Let's review what we learned in the previous article about the "inversion of Control" design, which is essentially "separating logic through interfaces."

But for the example above, there are some shortcomings in achieving this goal, first let's review the previous article's Code content

/// <summary>///This is a login-responsible interface type/// </summary> Public Interfaceiloginchecker{/// <summary>    ///login, required parameters are user name and password, need to return a bool type indicating whether the login was successful/// </summary>    /// <param name= "LoginName" ></param>    /// <param name= "password" ></param>    /// <returns></returns>    BOOLLogin (stringLoginName,stringpassword);} Public classloginwindow:form{PrivateIloginchecker Loginchecker; /// <summary>    ///decide which iloginchecker to use to take charge of the login process through the constructor function/// </summary>    /// <param name= "Chcker" ></param>     PublicLoginwindow (Iloginchecker chcker) { This. Loginchecker =Chcker; }    voidLoginbutton_click (Objectsender, EventArgs e) {        stringLoginName =NULL, password =NULL; //To take a value from a control//Judging null values//when everything is OK ,        if( This. Loginchecker.login (loginName, password)) {            //Login Successful        }        Else        {            //Logon Failure        }    }}

There must be some people with this kind of doubt: somewhere in the code there must be something like this:

/// instantiate a type that implements the Iloginchecker interface New  New  Loginwindow (checker); window. Show ();

Then with the later feature update, in the continuous modification here iloginchecker checker = new Xxxloginchecker ();

Long time, can't remember this code write where, is also very headache of one thing, the most important is, still not achieve "easy to maintain" the effect, and before the same, each need to change more, or environmental changes, all needs to rewrite this sentence.

It is much more convenient to have a container that can determine which iloginchecker type to use at Runtime (note 1) .

Runtime: Relative to "compile time", for example I say define a variable Int32 I, the type of I is Int32, which is determined at compile time, because the program is compiled from the code into a program, it can be determined that I is a Int32 type.

Another example is that I define a variable object obj, although the type of obj is an object, but according to the actual assignment, the type of transformation occurs, and what value is assigned to it, the program is not known at compile time, only when running here to know, this is called the runtime.

Let's assume a realistic scenario:

Scene, we put iloginchecker this interface

1, the guard is sent by the security company

2, the security company according to each demand side of the requirements of different, equipped with different security

3, security company has to meet various needs of security

In this way, we need to add a type of security company that is used to create Iloginchecker instances

So we have a name called Logincheckerfactory.

There is only one main method: Createloginchecker, depending on the name we specify, returns a specific Iloginchecker instance, let's take a look at the sample code:

classlogincheckerfactory{ PublicIloginchecker Createloginchecker (stringcheckername) {        Switch(checkername) { Case "Database":return NewDatabaseloginchecker ();//Login verification completed by the database             Case "WebService":return NewWebserviceloginchecker ();//Login verification completed by WebService             Case "TCP":return NewTcploginchecker ();//logon verification completed by TCP communication            default:Throw NewApplicationException ("Checker instance with this name does not exist"); }    }}

At this point, you will find that the login decision process is dependent on a string, database or WebService or TCP. At this point, I think most people understand that this string, as long as it's written in the config file, is done.

Then the project release, in the different environment, I just need to change the configuration file, you can achieve a variety of ways to login.

For the same ease of updating and maintenance, you can put different versions of Iloginchecker in this factory, and then change the instance based on some external version numbers.

In the bug correction, you also do not have to directly modify the type itself, you can copy a out, such as called WebServiceLoginChecker2, so that the program to ensure that the original operational, and the bug can be modified, once there is "moving one touch the whole body" situation, It's very easy to get out of the body.

Such design ideas, patterns, we call it the factory model. The factory model is also divided into simple Factory mode and abstract Factory mode, but its core idea is to create a factory that is dynamically created and returned by the factory at runtime. The coupling degree between class and class, module and module is greatly reduced, which provides a very good isolation environment for update and maintenance.

Summary

Through the first and second articles of learning, a preliminary framework of ideas has been generated.

1, the main things to analyze the current method

2, the possibility of changes in the logic, the establishment of interfaces, to be implemented later

3, considering the implementation of the above-mentioned interface diversity, the establishment of plant type, by the factory type responsible for creating interface instances

Trade-offs between pros and cons

From the perspective of making products , a good basic framework is the product of the core of the guarantee, with such a guarantee, it can be said, unless you change the language of the day, otherwise will never exist (re-start) that day, because each of your links are low coupling, they can all be replaced alone.

From the perspective of the project , a good basic framework is the most time-consuming and cost-consuming phase of the project. In the eyes of the result-oriented project leader, relative to the maintainability progress is the most important, so in the case of the project, the use of the architecture should be a speed and quality tradeoff.

Article for the author original, reproduced please indicate the source, thank you http://www.cnblogs.com/ShimizuShiori/p/4929300.html

What is an interface (intermediate)--the use of interfaces in design mode (ii)

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.