Java design Pattern (10) Single Responsibility principle (SRP)

Source: Internet
Author: User

Single Responsibility Principle basic concept of the SRP

Single principle of responsibility

    • definition : There should be and only one reason for the change of the class, that is, the interface or class and responsibility relationship is one by one corresponding .
    • Difficulty : Division of Duties:
      • We have different responsibilities in different situations and production environments (a single relativity of duties )
      • The principle of single responsibility is a standard for evaluating whether an interface is good, but the reasons for responsibility and change are not measurable , vary by project and vary by environment ( non-measurable )
    • Advantages :
      • The complexity of classes is reduced : each class or interface implements only a single responsibility, clearly defined
      • improved readability : clearly defined, naturally resulting in higher code readability
      • improved maintainability : Code readable, easier to understand, natural and easy to maintain, and a single responsibility so the class between the low coupling , so easier to modify.
      • Extensibility is better : There is a new responsibility to expand, just inherit the corresponding interface to implement a new implementation.
Example of SRP

Because object-oriented programming is to promote interface-oriented programming , our external exposure to the method is best defined as an interface, and then by the specific class to implement, many of the benefits are no longer mentioned, we are based on a simple scenario to design, reflecting the benefits of a single responsibility:

Definition of the scene

For example, pear is an electronic product, it is to produce pad,phone,watch and other equipment, but there are some repetitive functions , if the design of a separate set, it is clearly not cost-effective, then the interface definition we can set up a single function according to functional division The interface:

Definition of the interface
//可以拨打电话interface Callable{    void call ();}//可以触摸控制interface Touchable{    void touch();}//可以消息提醒interface MessagePromptable{    void prompt();}//可以接入键盘interface KeyBoardMatchable{    void match();}
The class that implements the interface is still a single responsibility
 class standardcall implements callable{@Override Public voidCall () {System.out.println ("Call to somebody!"); }} class Standardtouch implements touchable{@Override Public voidTouch () {System.out.println ("Touch to press the button!"); }} class standardpromt implements messagepromptable{@Override Public voidPrompt () {System.out.println ("Someone contact to you,sir!"); }} class standardmatch implements keyboardmatchable{@Override Public voidMatch () {System.out.println ("The KeyBoard is ready to work!"); }}
Production of products
    • If we produce a cell phone based on our existing technology, then we need it to call , touch screen control and message alert :
//When declaring this phone, we know exactly what it's capable of .Class Myphone implements callable,messagepromptable,touchable{//No need to re-develop existing technology, direct loading can    PrivateCallable caller =NewStandardcall ();PrivateMessagepromptable prompter =NewSTANDARDPROMT ();PrivateTouchable Toucher =NewStandardtouch ();@Override     Public void Pager() {caller.call (); }@Override     Public void prompt() {prompter.prompt (); }@Override     Public void Touch() {Toucher.touch (); }} Public  class srptest {     Public Static void Main(String [] args) {Myphone phone =NewMyphone ();        Phone.call ();        Phone.prompt ();    Phone.touch (); }}
    • If we need a new phone, but we just have a new call technology, then only need to implement this technology to inherit the callable interface, and then before the cell phone callable specific is the murder class replaced with new technology can, only need to modify a line of code, is not feeling great. The single responsibility is constrained by our impact on changes to existing classes
    • So if I want to produce a pad, the same Ah, only need to be loaded in the existing technology can ah, pad class is still only a single integration technology to form the responsibility of the product, integration into the product and research and development of technology , separation of duties, For the expansion of our class to bring convenience
class MyPad implements Touchable,KeyBoardMatchable{    new StandardTouch();    new StandardMatch();    @Override    publicvoid match() {        toucher.touch();    }    @Override    publicvoid touch() {        matcher.match();    }}
Summarize

In the case of the above denomination, there can be a clearer understanding, in fact, if a single interface provides an implementation class will result in a large number of classes, it is inconvenient to use, so we can integrate some functions. Nutshell:

for a single responsibility principle, the interface must be a single responsibility, the design of the class as far as possible only one cause of change
    • In the following example, our interface is still a single function, but the ability to answer and make calls is often non-divided and they change at the same time, so we can provide an implementation class that inherits two interfaces at the same time.
 class callandprompt implements callable,messagepromptable{@Override Public voidCall () {System.out.println ("Hello, I had some thing to tell You!"); } @Override Public voidPrompt () {System.out.println ("Hello,what do you want to tell me!"); }}//When declaring this phone, we know exactly what it's capable of . class myphone implements callable,messagepromptable,  Touchable{    //No need to re-develop existing technology, direct loading can    PrivateCallable caller =NewCallandprompt ();//different interfaces invoke different functions of the same implementation class    PrivateMessagepromptable prompter = (messagepromptable) caller;PrivateTouchable Toucher =NewStandardtouch (); @Override Public voidCall () {Caller.call (); } @Override Public voidPrompt () {prompter.prompt (); } @Override Public voidTouch () {Toucher.touch (); }}

From the above example, you may be more likely to understand my summary. But the principle of this thing to abide by, but there is no need to cling to . In the actual design still need to learn to work. After all, the classic design pattern does not always follow these design principles, but they are still widely used in the actual, but also good performance

Java design Pattern (10) Single Responsibility principle (SRP)

Related Article

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.