6 design principles of the opening and closing principle. __ Design mode

Source: Internet
Author: User

Defined:

A software entity such as classes, modules, and functions should be open to extensions and closed for modification.


The definition of the opening and closing principle has clearly told us that software entities should be open to extensions and closed to modifications, meaning that a software entity should implement changes through extensions rather than modifying existing code to achieve change. So what is a software entity? Software entities include the following sections:

A module in a project or software product that is divided according to certain logical rules. Abstractions and classes. Method. The opening and closing principle tells us to change the behavior of the software entity as far as possible, instead of modifying the existing code to complete the change, it is a principle for the future event of the software entity to constrain the current development design.

Book Interface

Public interface IBook {

Books have a name

Public String getName ();

Books have a price

public int getprice ();

Books have authors

PULIBC String Getauthor ();

}

Fiction class

public class Noveibook implements ibook {

Book Name

private String name;

The price of a book

private int price;

The author of the book

Private String author;

Passing book data through constructors

Public Novebook (string _name, int _price, string _author) {

THIS.name = _name;

This.price = _price;

This.author = _author;

}

Get who the author is

Public String Getauthor () {

return this.author;

}

What's the name of the book?

Public String GetName () {

return this.name;

}

Get the price of a book

public int GetPrice () {

return this.price;

}

}

Note: We define the price as int type is not wrong, in non-financial projects in the currency processing, generally take 2-bit precision, the usual design method in the operation of the expansion of 100 times times in the need to show the reduction of 100 times times, reduce the error caused by precision.

Books for sale in bookstores

public class Bookstore {

Private final static arraylist<ibook> Booklist = new arraylist<ibook> ();

Statically static modules initialize data, which is typically done by the persistence layer in the actual project

static {

Booklist.add (New Noveibook ("Tianlong Eight", 3200, "Jin Yong"));

Booklist.add (New Offnoveibook ("Notre Dame Cathedral", 5600, "Hugo"));

Booklist.add (New Offnoveibook ("Miserable World", 3500, "Hugo"));

Booklist.add ("Computerbook", 4300, "Bruce Eckel", "programming Language"));

}

Buy books in a simulated bookstore

public static void Main (string[] args) {

NumberFormat formatter = Numberformat.getcurrencyinstance ();

Formatter.setmaximumfractiondigits (2);

System.out.println ("Books sold---------------------bookstores are recorded as follows:------------------");

for (ibook book:booklist) {

System.out.println ("Book Name:" + book.getname () + "T book author:" + book.getauthor () + "T book Price:" + Formatter.format (Book.getprice ( )/100.0) + "Yuan");

}

}

}

A novel of discounted sales

public class Offnoveibook extends Noveibook {

Public Offnoveibook (string _name, int _price, String _author,) {

Super (_name, _price, _author);

}

Overwrite Sales price

@Override

public int GetPrice () {

Price

int selfprice = Super.getprice ();

int offprice = 0;

Int (Selfprice > 4000) {//The original price is more than 40 yuan, then call 90 percent

Offprice = Selfprice * 90/100;

} else {

Offprice = selfprice*80/100;

}

return offprice;

}

}

Note: The opening and closing principle to expand Open, to modify the closure, does not mean that no changes, the underlying module changes, must have a high level module to be coupled, otherwise it is an isolated meaningless code fragment.

We can generalize the changes into the following three categories:

Logic changes as long as the change of a logic, and does not involve other modules, such as the original algorithm is a*b+c, now need to modify to A*b*c, you can modify the methods in the original class to complete the method, provided that all dependent or associated classes are in accordance with the same logic. The Sub module changes a module, will have an impact on other modules, especially a low-level module changes will inevitably lead to the changes in the high-level module, so the completion of changes through the extension, the high level of the module to modify the inevitable, just the book discount processing is similar to the processing module, this part of the changes may even cause changes in the interface. Visible view changes visible view is the interface provided to customers, such as JSP programs, swing interface, and so on, this part of the change in general can cause a ripple effect. The basic path of a project should be this: project development, refactoring, testing, commissioning, operation, the reconstruction of which can modify the original design and code, operation and maintenance to minimize the original code changes, maintain the purity of historical code, improve the stability of the system. According to the Java language, the opening and closing principle is an abstract class, the other five principles are concrete implementation classes. The principle of opening and closing is very important, and it can be understood by the following several aspects to understand its importance. 1, the opening and closing principle of the impact of the test 2, the open and closed principle can improve the reusability of the logical granularity, until a logic can not be split. 3, opening and closing principle can improve the maintenance of 4, object-oriented development needs. How to use the open and close principle: 1, abstract constraint abstraction is a common description of a group of things, no specific implementation, also means that he can have a lot of possibilities, can follow the changes in demand. Thus, an interface or abstract class can constrain a set of behaviors that may change, and can realize to expand Open, it contains three layers of meaning: first, through the interface or abstract class constraints extension, bounds on the extension, not allowed to appear in the interface or abstract classes do not exist public methods; Reference objects use interfaces or abstract classes as much as possible, rather than implementing classes. Third, the abstraction layer remains as stable as possible, and modification is not allowed once it is determined. Computer book interface public interface Icomputerbook extends ibook {//computer book is a scope public String getscope ();} Computer book class public classes Compu Terbook implements Icomputerbook {private string name, private string scope, private string author, private int price PU Blic Computerbook (String _name, inT _price,  string _author,  String _scope) {this.name =_name; this.price = _price; . scope = _scope; public string Getscope () {return This.scope ():} public string Getauthor () {return this.author.} public String Getnam E () {return this.name  } public int getprice ()} The first prerequisite for the expansion of openness is abstract constraints.
2. Meta data (metadata) control module behavior what is metadata. Data used to describe the environment and data, in layman's terms, configuration parameters, parameters can be obtained from the file, can also be obtained from the database. 3, the formulation of the project Charter for the project, the agreement is better than the configuration. 4, package changes to change the package contains two meanings: first, encapsulate the same changes into an interface or abstract class, and second, encapsulate different changes into different interfaces or abstract classes, and there should not be two different changes appearing in the same interface or abstract class. Package changes, that is, protected changes, identify the points that are expected to change or be unstable, we create a stable interface for these points of change, and accurately encapsulate possible changes that can be encapsulated once a prediction or a "Sixth sense" notice changes, and 23 design patterns are encapsulated from different angles.
Best practices: The biggest challenge in software design is coping with changes in demand, but the complexity of changing demand is unpredictable. It's a very painful thing to be prepared for unforeseen things, but the gurus have given us a very good 6 design principles and 23 design patterns to "encapsulate" future changes, and we've talked about the following design principles in the first 5 chapters. Single responsibility Principle: principle of sole responsibility
Open colsed Principle: Closing principle Liskov Substitution principle: Richter Replacement Principle Law of Demeter: Dimitri rules Interface segregation principle: interface Isolation Principle dependence inversion principle: the principle of dependency inversion the first letter of the 6 principles (the Richter replacement principle and the Dimitri law of the first letter, only one) together is solid (solid, stable), The implication of its representative is that the 6 principles of the use of the benefits: the establishment of a stable, flexible, robust design, and the opening and closing principle is the most important, is the most basic principle, is the other 5 principles of spiritual leaders. We need to pay attention to the following problems when we use the open and closing principle. The opening and closing principles are just a principle. Project regulations are very important to anticipate change

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.