


An introduction to the seven principles of object-oriented design in C#
1: Single Responsibility Principle (SRP)
1. Definition: An object should only contain a single responsibility, and the responsibility is completely encapsulated in a class
Or: As far as a class is concerned, there should be only one reason for its change.
2. Analysis: The more responsibilities a class (or as large as a module or as small as a method) bears, the less likely it is to be reused, and if a class bears too many responsibilities, it will be quite Due to coupling these responsibilities together, when one of the responsibilities changes, it may affect the operation of other responsibilities. The responsibilities of a class mainly include two aspects: data responsibilities and behavioral responsibilities. Data responsibilities are reflected through its attributes, while behavioral responsibilities are reflected through its methods. The single responsibility principle is a guideline for achieving high cohesion and low coupling. It can be found in many code refactoring techniques. It is the simplest but most difficult principle to apply. It requires designers to discover the different responsibilities of classes and Separating them and discovering the multiple responsibilities of classes requires designers to have strong analysis and design capabilities and relevant refactoring experience.
3. Example:
The example shows that the "login function" of a Java-based C/S system is implemented through the following login class (Login):
The single responsibility principle is now used for it Refactor.
2: Open-Closed Principle (OCP)
1. Definition: A software entity should be open to extensions and closed to modifications. That is to say, when designing a module, the module should be extended without being modified, that is, the behavior of the module can be changed without modifying the source code.
2. Analysis: The opening and closing principle was proposed by Bertrand Meyer in 1988. It is one of the most important principles in object-oriented design. In the definition of the open-closed principle, a software entity can refer to a software module, a partial structure composed of multiple classes, or an independent class. Abstraction is key to the Open/Closed Principle. The opening and closing principle can also be described by a more specific "Principle of Encapsulation of Variation". The Principle of Encapsulation of Variation (EVP) requires finding the variable factors of the system and encapsulating them.
3: Liskov Substitution Principle (LSP)
1. Definition: If for every object o1 of type S, there is an object o2 of type T, So that the behavior of all programs P defined with T does not change when all objects o1 are replaced with o2, then type S is a subtype of type T
Or: all reference base classes (parent Class) must be able to transparently use objects of its subclasses.
2. Analysis: The Liskov substitution principle was developed by Barbara Liskov, the 2008 Turing Award winner, the first female doctor of computer science in the United States, professor at MIT, and Professor Jeannette Wing at Carnegie Mellon University. Proposed in 1994.
The Liskov substitution principle can be expressed in a popular way: if you can use base class objects in software, then you must be able to use its subclass objects. If the base class is replaced with its subclasses, the program will not generate any errors or exceptions. The reverse is not true. If a software entity uses a subclass, it may not be able to use the base class. The Liskov substitution principle is one of the important ways to implement the opening and closing principle. Since subclass objects can be used wherever base class objects are used, try to use base class types to define objects in the program, and then use them at runtime. Determine its subclass type and replace the parent class object with the subclass object.
4: Dependence Inversion Principle (DIP)
1. Definition: High-level modules should not rely on low-level modules, they should all rely on abstraction. Abstraction should not depend on details, details should depend on abstraction
Or: Program for interfaces, not implementations. (Program to an interface, not an implementation.)
2. Analysis: The Dependency Inversion Principle is the third column of Engineering Notebook written by Robert C. Martin for "C++ Reporter" in 1996, and was later added To his classic book "Agile Software Development, Principles, Patterns, and Practices" published in 2002.
Simply put, the principle of dependency inversion means: code should depend on abstract classes, not concrete classes; programming should be for interfaces or abstract classes, not for concrete classes. The key to realizing the opening and closing principle is abstraction, and concrete implementation is derived from abstraction. If the opening and closing principle is the goal of object-oriented design, then the dependency inversion principle is the main method of object-oriented design.
One of the common ways to implement the dependency inversion principle is to use abstract classes in the code and place concrete classes in the configuration file.
Coupling between classes
Zero coupling relationship
Concrete coupling relationship
Abstract coupling relationship
Dependency inversion principle requires the client Depend on abstract coupling Coupling in an abstract way is the key to the dependency inversion principle.
Dependency Injection
Constructor Injection: Inject instance variables through the constructor.
Setter Injection: Inject instance variables through the Setter method.
Interface Injection: Inject instance variables through interface methods.
5: Interface Segregation Principle (ISP)
1. Definition: The client should not rely on interfaces that it does not need. Note that the interface in this definition refers to defined method.
Or: Once an interface is too large, it needs to be divided into smaller interfaces. The client using the interface only needs to know the methods related to it.
2. Analysis: The principle of interface isolation refers to using multiple specialized interfaces instead of using a single total interface. Each interface should assume a relatively independent role, no more and no less. It should not do things that it should not do, but should do everything that should be done.
(1) An interface only represents one role, and each role has its own specific interface. This principle can be called the "role isolation principle".
(2) The interface only provides the behaviors that the client needs, that is, the required methods. The behaviors that the client does not need are hidden. The client should be provided with a separate interface as small as possible instead of providing Large overall interface.
When using the interface isolation principle to split an interface, you must first satisfy the single responsibility principle, define a set of related operations in an interface, and on the premise of meeting high cohesion, the fewer methods in the interface The better. You can use customized services when designing the system, that is, providing interfaces with different widths for different clients, only providing the behaviors that users need, and hiding the behaviors that users do not need.
6: Composite Reuse Principle (CRP), also known as Composition/ Aggregate Reuse Principle (CARP)
1. Definition: Use objects as much as possible Composition rather than inheritance to achieve reuse. (Favor composition of objects over inheritance as a reuse mechanism.)
2. Analysis: The principle of composition and reuse refers to using some existing objects in a new object through association relationships (including combination relationships and aggregation relationships) existing objects, making them part of a new object; the new object achieves the purpose of reusing its existing functions by delegating and calling methods of existing objects. In short: Use composition/aggregation relationships as much as possible and inheritance less often.
In object-oriented design, existing designs and implementations can be reused in different environments through two basic methods, namely through composition/aggregation relationships or through inheritance.
Inheritance and reuse: simple to implement and easy to extend. Destroys the encapsulation of the system; the implementation inherited from the base class is static, cannot be changed at runtime, and does not have enough flexibility; it can only be used in limited environments. ("White box" reuse)
Combination/aggregation reuse: The degree of coupling is relatively low, and the operations of member objects are selectively called; it can be done dynamically at runtime. ("Black box" reuse)
Combination/aggregation can make the system more flexible, reduce the coupling between classes, and changes in one class have relatively little impact on other classes, so combination/aggregation is generally preferred. To achieve reuse; secondly consider inheritance. When using inheritance, you need to strictly follow the Liskov substitution principle. Effective use of inheritance will help understand the problem and reduce complexity, while abuse of inheritance will increase system construction and maintenance. The difficulty and complexity of the system require careful use of inheritance reuse.
7: Law of Demeter (LoD), also known as Least Knowledge Principle (LKP)
1. Definition:
(1 ) Don’t talk to “strangers.” The English definition is: Don't talk to strangers.
(2) Only communicate with your direct friends. The English definition is: Talk only to your immediate friends.
(3) Each software unit has minimal knowledge of other units and is limited to those software units that are closely related to its own unit. The English definition is: Each unit should have only limited knowledge about other units: only units "closely" related to the current unit.
2. Analysis: Demeter's law comes from Northeastern University in the autumn of 1987 ) a research project called "Demeter". Simply put, Demeter's Law means that a software entity should interact with other entities as little as possible. In this way, when one module is modified, it will affect other modules as little as possible, and expansion will be relatively easy. This is a restriction on communication between software entities. It requires limiting the width and depth of communication between software entities.
The above is the detailed content of An introduction to the seven principles of object-oriented design in C#. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



According to news on March 4, Kubi Rubik's Cube will launch the "Xiaoku Tablet 2Lite" tablet computer on March 5, with an initial price of 649 yuan. It is reported that the new tablet is equipped with Unisoc’s T606 processor, which uses a 12nm process and consists of two 1.6GHz ArmCortex-A75 CPUs and six ArmCortex-A55 processors. The screen uses a 10.95-inch IPS eye-protection screen with a resolution of 1280x800 and a brightness as high as 350 nits. In terms of imaging, Xiaoku Tablet 2Lite has a 13-megapixel main camera on the rear and a 5-megapixel selfie lens on the front. It also supports 4G Internet access/calls, Bluetooth 5.0, and Wi-Fi5. In addition, the official claimed that this tablet&l

According to news on April 26, ZTE’s 5G portable Wi-Fi U50S is now officially on sale, starting at 899 yuan. In terms of appearance design, ZTE U50S Portable Wi-Fi is simple and stylish, easy to hold and pack. Its size is 159/73/18mm and is easy to carry, allowing you to enjoy 5G high-speed network anytime and anywhere, achieving an unimpeded mobile office and entertainment experience. ZTE 5G portable Wi-Fi U50S supports the advanced Wi-Fi 6 protocol with a peak rate of up to 1800Mbps. It relies on the Snapdragon X55 high-performance 5G platform to provide users with an extremely fast network experience. Not only does it support the 5G dual-mode SA+NSA network environment and Sub-6GHz frequency band, the measured network speed can even reach an astonishing 500Mbps, which is easily satisfactory.

According to news on April 17, HMD teamed up with the well-known beer brand Heineken and the creative company Bodega to launch a unique flip phone - The Boring Phone. This phone is not only full of innovation in design, but also returns to nature in terms of functionality, aiming to lead people back to real interpersonal interactions and enjoy the pure time of drinking with friends. Boring mobile phone adopts a unique transparent flip design, showing a simple yet elegant aesthetic. It is equipped with a 2.8-inch QVGA display inside and a 1.77-inch display outside, providing users with a basic visual interaction experience. In terms of photography, although it is only equipped with a 30-megapixel camera, it is enough to handle simple daily tasks.

According to news on July 12, the Honor Magic V3 series was officially released today, equipped with the new Honor Vision Soothing Oasis eye protection screen. While the screen itself has high specifications and high quality, it also pioneered the introduction of AI active eye protection technology. It is reported that the traditional way to alleviate myopia is "myopia glasses". The power of myopia glasses is evenly distributed to ensure that the central area of sight is imaged on the retina, but the peripheral area is imaged behind the retina. The retina senses that the image is behind, promoting the eye axis direction. grow later, thereby deepening the degree. At present, one of the main ways to alleviate the development of myopia is the "defocus lens". The central area has a normal power, and the peripheral area is adjusted through optical design partitions, so that the image in the peripheral area falls in front of the retina.

According to news on April 3, Taipower’s upcoming M50 Mini tablet computer is a device with rich functions and powerful performance. This new 8-inch small tablet is equipped with an 8.7-inch IPS screen, providing users with an excellent visual experience. Its metal body design is not only beautiful but also enhances the durability of the device. In terms of performance, the M50Mini is equipped with the Unisoc T606 eight-core processor, which has two A75 cores and six A55 cores, ensuring a smooth and efficient running experience. At the same time, the tablet is also equipped with a 6GB+128GB storage solution and supports 8GB memory expansion, which meets users’ needs for storage and multi-tasking. In terms of battery life, M50Mini is equipped with a 5000mAh battery and supports Ty

At work, ppt is an office software often used by professionals. A complete ppt must have a good ending page. Different professional requirements give different ppt production characteristics. Regarding the production of the end page, how can we design it more attractively? Let’s take a look at how to design the end page of ppt! The design of the ppt end page can be adjusted in terms of text and animation, and you can choose a simple or dazzling style according to your needs. Next, we will focus on how to use innovative expression methods to create a ppt end page that meets the requirements. So let’s start today’s tutorial. 1. For the production of the end page, any text in the picture can be used. The important thing about the end page is that it means that my presentation is over. 2. In addition to these words,

According to news on May 13, vivoX100s was officially released tonight. In addition to excellent images, the new phone also performs very well in terms of signal. According to vivo’s official introduction, vivoX100s uses an innovative universal signal amplification system, which is equipped with up to 21 antennas. This design has been re-optimized based on the direct screen to balance many signal requirements such as 5G, 4G, Wi-Fi, GPS, and NFC. This makes vivoX100s the mobile phone with the strongest signal reception capability in vivo’s history. The new phone also uses a unique 360° surround design, with antennas distributed around the body. This design not only enhances the signal strength, but also optimizes various daily holding postures to avoid problems caused by improper holding methods.

According to news on July 29, the Honor X60i mobile phone is officially on sale today, starting at 1,399 yuan. In terms of design, the Honor X60i mobile phone adopts a straight screen design with a hole in the center and almost unbounded ultra-narrow borders on all four sides, which greatly broadens the field of view. Honor X60i parameters Display: 6.7-inch high-definition display Battery: 5000mAh large-capacity battery Processor: Dimensity 6080 processor (TSMC 6nm, 2x2.4G A76+6×2G A55) System: MagicOS8.0 system Other features: 5G signal enhancement, smart capsule, under-screen fingerprint, dual MIC, noise reduction, knowledge Q&A, photography capabilities: rear dual camera system: 50 million pixels main camera, 2 million pixels auxiliary lens, front selfie lens: 8 million pixels, price: 8GB
