In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly explains "what are the six principles of JS design pattern". Interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn what are the six principles of JS design pattern.
Single responsibility principle (SRP)
Single function principle: the single function principle holds that the object should only have the concept of a single function.
In other words, let a class do only one type of responsibility, and when the class needs to take on other types of responsibility, it needs to decompose the class. Of all the SOLID principles, this is the one that most developers feel most fully understood. Strictly speaking, this may also be one of the most frequently violated principles. The principle of single responsibility can be regarded as an extension of the object-oriented principle of low coupling and high cohesion. Responsibility is defined as the cause of change in order to improve cohesion to reduce the cause of change. Too much responsibility, the more reasons that may cause it to change, which will lead to responsibility dependence, which will have an impact on each other, thus greatly damaging its cohesion and coupling. A single responsibility usually means a single function, so don't show too many function points for a module to ensure that the entity has only one reason for its change.
"A bad way to write."
Class UserSettings {constructor (user) {this.user = user;} changeSettings (settings) {if (this.verifyCredentials ()) {/ /...}} verifyCredentials () {/ /...}}
"good way to write."
Class UserAuth {constructor (user) {this.user = user;} verifyCredentials () {/ /...}} class UserSettings {constructor (user) {this.user = user; this.auth = new UserAuth (user);} changeSettings (settings) {if (this.auth.verifyCredentials ()) {/ /.}
Principle of opening and closing (OCP)
Software entities should be extensible, not modifiable. That is, it is open to extensions and closed to modifications. This principle is the most abstract and difficult to understand among the many principles of object-oriented programming.
Extend functionality by adding code, rather than modifying existing code.
If the customer module and the service module follow the same interface, the customer module can not care about the type of the service module, and the service module can easily expand the service (code).
OCP supports replacement services without modifying the customer module.
The vernacular is: don't you want to change? so I'll let you inherit and implement an object and abstract your responsibilities with an interface. The more changes you have, the more subclasses you inherit from the implementation.
"A bad way to write."
Class AjaxAdapter extends Adapter {constructor () {super (); this.name = "ajaxAdapter";}} class NodeAdapter extends Adapter {constructor () {super (); this.name = "nodeAdapter";}} class HttpRequester {constructor (adapter) {this.adapter = adapter } fetch (url) {if (this.adapter.name = "ajaxAdapter") {return makeAjaxCall (url) .then (response = > {/ / transform response and return});} else if (this.adapter.name = "nodeAdapter") {return makeHttpCall (url) .then (response = > {/ / transform response and return}) }} function makeAjaxCall (url) {/ / request and return promise} function makeHttpCall (url) {/ / request and return promise}
"good way to write."
Class AjaxAdapter extends Adapter {constructor () {super (); this.name = "ajaxAdapter";} request (url) {/ / request and return promise}} class NodeAdapter extends Adapter {constructor () {super (); this.name = "nodeAdapter";} request (url) {/ / request and return promise}} class HttpRequester {constructor (adapter) {this.adapter = adapter } fetch (url) {return this.adapter.request (url) .then (response = > {/ / transform response and return});}}
Richter substitution principle (LSP)
Richter substitution principle: the Richter substitution principle holds that "objects in a program should be replaceable by its subclasses without changing the correctness of the program".
LSP gives us a benchmark for judging and designing the relationship between classes: whether inheritance is needed and how to design inheritance relationships.
An is-A relationship exists only when an instance of a subclass should be able to replace any instance of its superclass. Inheritance for "OCP" is equivalent to polymorphism for the Richter scale substitution principle. Subclasses can replace base classes, customers use base classes, and they don't need to know what derived classes do. This is an alternative principle for behavioral responsibility, and if S is a subtype of T, then S objects should replace all T objects without changing any abstract properties.
The customer module should not care about how the service module works; the same interface modules can be replaced without knowing the service module code. That is, where the interface or parent class appears, the class or subclass that implements the interface can be substituted.
"A bad way to write."
Class Rectangle {constructor () {this.width = 0; this.height = 0;} setColor (color) {/ /...} render (area) {/ /...} setWidth (width) {this.width = width;} setHeight (height) {this.height = height;} getArea () {return this.width * this.height }} class Square extends Rectangle {setWidth (width) {this.width = width; this.height = width;} setHeight (height) {this.width = height; this.height = height;}} function renderLargeRectangles (rectangles) {rectangles.forEach (rectangle = > {rectangle.setWidth (4); rectangle.setHeight (5); const area = rectangle.getArea (); / / BAD: Returns 25 for Square. Should be 20. Rectangle.render (area);} const rectangles = [new Rectangle (), new Rectangle (), new Square ()]; renderLargeRectangles (rectangles)
"good way to write."
Class Shape {setColor (color) {/ /...} render (area) {/ /...} class Rectangle extends Shape {constructor (width, height) {super (); this.width = width; this.height = height;} getArea () {return this.width * this.height;}} class Square extends Shape {constructor (length) {super () This.length = length;} getArea () {return this.length * this.length;}} function renderLargeShapes (shapes) {shapes.forEach (shape = > {const area = shape.getArea (); shape.render (area);});} const shapes = [new Rectangle (4,5), new Rectangle (4,5), new Square (5)]; renderLargeShapes (shapes)
Interface isolation principle (ISP)
Interface isolation principle: the interface isolation principle holds that "multiple specific client interfaces are better than a broad-purpose interface".
Users cannot be forced to rely on interfaces they do not use. In other words, it is better to use multiple specialized interfaces than to use a single master interface.
This principle originated from Xerox, which needed to build a new printer system that could perform tasks such as binding a set of printed matter and faxing. The creation of this system software starts from the bottom and realizes these task functions, but the growing software functions make it more and more difficult for the software itself to adapt to change and maintenance. With every change, even the smallest change, someone may need nearly an hour to recompile and redeploy. It was almost impossible to continue to develop, so they hired Robert Robert to help them. They first designed a major class, Job, which can be used to implement almost all task functions. As long as you call a method of the Job class, you can realize a function. The Job class changes a lot, and it is a fat model. For the client, if only one printing function is needed, but other independent printing method functions are also coupled with it, the ISP principle suggests adding an interface layer between the client and the Job class. There are different interfaces for different functions, such as printing function is the Print interface. Then cut the large Job class into subclasses that inherit different interfaces, so there is a Print Job class, and so on.
"A bad way to write."
Class DOMTraverser {constructor (settings) {this.settings = settings; this.setup ();} setup () {thisthis.rootNode = this.settings.rootNode; this.animationModule.setup ();} traverse () {/ /...}} const $= new DOMTraverser ({rootNode: document.getElementsByTagName ("body"), animationModule () {} / / Most of the time, we won't need to animate when traversing. / /.})
"good way to write."
Class DOMTraverser {constructor (settings) {this.settings = settings; this.options = settings.options; this.setup ();} setup () {thisthis.rootNode = this.settings.rootNode; this.setupOptions () } setupOptions () {if (this.options.animationModule) {/ /...}} traverse () {/ /...}} const $= new DOMTraverser ({rootNode: document.getElementsByTagName ("body"), options: {animationModule () {})
Dependency inversion principle (DIP)
Dependency inversion principle: the dependency inversion principle holds that a method should follow the concept of "relying on abstraction rather than an instance". Dependency injection is one way to implement this principle.
The principle of dependency inversion (Dependency Inversion Principle,DIP) states that code should depend on abstract concepts, not concrete implementations.
High-level modules should not rely on lower-level modules
Both high-level and low-level modules rely on abstraction
Abstraction does not depend on concrete implementation
Concrete implementation depends on abstraction
Abstractions and interfaces separate dependencies between modules
Class may depend on other classes to perform its work. However, they should not rely on a specific implementation of the class, but rather on its abstraction. This principle is really too important, social division of labor, standardization are the embodiment of this design principle. Obviously, this concept will greatly improve the flexibility of the system. If classes only care about their use to support specific contracts rather than specific types of components, you can quickly and easily modify the functionality of these low-level services while minimizing the impact on the rest of the system.
"A bad way to write."
Class InventoryRequester {constructor () {this.REQ_METHODS = ["HTTP"];} requestItem (item) {/ /...}} class InventoryTracker {constructor (items) {this.items = items; / / BAD: We have created a dependency on a specific request implementation. / / We should just have requestItems depend on a request method: `request`this.requester = new InventoryRequester ();} requestItems () {this.items.forEach (item = > {this.requester.requestItem (item);});}} const inventoryTracker = new InventoryTracker (["apples", "bananas"]); inventoryTracker.requestItems ()
"good way to write."
Class InventoryTracker {constructor (items, requester) {this.items = items; this.requester = requester;} requestItems () {this.items.forEach (item = > {this.requester.requestItem (item);});}} class InventoryRequesterV1 {constructor () {this.REQ_METHODS = ["HTTP"] } requestItem (item) {/ /...}} class InventoryRequesterV2 {constructor () {this.REQ_METHODS = ["WS"];} requestItem (item) {/ /...}} const inventoryTracker = new InventoryTracker (["apples", "bananas"], new InventoryRequesterV2 ()); inventoryTracker.requestItems () At this point, I believe you have a deeper understanding of "what are the six principles of JS design pattern". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.