当前位置:网站首页>Bao Yan notes II software engineering and calculation volume II (Chapter 13-16)
Bao Yan notes II software engineering and calculation volume II (Chapter 13-16)
2022-07-05 23:37:00 【Bulbuli egg】
Catalog
The first 13 Chapter Modularization and information hiding in detailed design
1. Coupling and Cohesion ( A term is used to explain )
2. Basic idea of information hiding
The first 14 Chapter Object oriented modularity
14.1.1 Implicit coupling :Cascading Message Cascading call problem
14.2.1. Programming to an interface
14.2.2. Minimize the interface / Interface separation principle
14.4.1.liskov Substitution principle
14.4.2. Combining alternative inheritance
14.4. Ways to improve cohesion
14.4.1. Principle of single responsibility (SRP)
14.5.Summary:Principles from Modularization The principle of modularity
The first 15 Chapter Object oriented information hiding
15.1. The meaning of information hiding
15.3. Opening and closing principle OCP
15.4. The principle of Dependence Inversion DIP
The first 16 Chapter Design patterns
16.1. How to achieve modifiability 、 Extensibility 、 flexibility
16.2 Design patterns and Strategy Pairing
Reference resources : Nanruan postgraduate entrance examination book , Soft work II
This big guy :Blog of Samperson (samperson1997.github.io)
And this big guy :SpriCoder The blog of
The first 13 Chapter Modularization and information hiding in detailed design
1. Coupling and Cohesion ( A term is used to explain )
(1) coupling
It describes the complexity of the relationship between two modules .
Coupling is divided into several levels according to its coupling from high to low : The higher the module coupling , The worse the division of modules , The more unfavorable it is for software change and reuse .1、2、3 Unacceptable ,4、5 Acceptable ,6 optimal
(1) Content coupling ( One module directly modifies the contents of another module , Such as GOTO sentence ; Some language mechanisms support changing the code of another module directly ; Change the internal data of another module )
(2) Public coupling ( Global variables , Global data is shared between modules , Example : Global variables )
(3) Repeated coupling ( There are duplicate codes between modules )
(4) Control coupling ( One module transmits control information to another module , Such as “ Explicit Sunday ”)
(5) Imprint coupling ( The shared data structure only uses one part )
(6) Data coupling ( Parameter transmission between modules only transmits the required data , optimal )
(2) cohesion
It expresses the tightness of the connection within a module .
Cohesion from high to low is divided into : The higher the cohesion, the better , The lower it is, the harder it is to realize change and reuse ,3、4、5 Equivalent ,1、2 best ,6、7 Can't accept .
(1) informational cohesion ( The module performs many operations , Each has its own entry point , Each operation code is relatively independent , And all operations are carried out on the same data structure : Such as stack )
(2) Functional cohesion ( Perform only one operation or achieve one purpose )
(3) Communication cohesion ( Perform different operations on the same data : Check the title 、 Check the author 、 Check the publisher )
(4) Process cohesion ( Related to steps : The goalkeeper passes the ball to the defender 、 The defender passes to the midfielder 、 The midfielder passes to the striker )
(5) Time converges ( It's about time : Get out of bed 、 Brush one's teeth 、 wash one 's face 、 to have breakfast )
(6) Logical cohesion ( A series of replaceable operations : Such as taking a car 、 Take a plane )
(7) To gather by chance ( Multiple unrelated operations : Car repair 、 to toast bread 、 Walk the dog 、 See a movie )
【 Question type 】 For instance , Explain the degree of coupling and cohesion between them , Give reasons . Book P226 exercises
2. Basic idea of information hiding
Each module hides an important design decision —— duty . The responsibility is embodied as a contract of the module , And under this contract, there are only decisions or secrets that this module knows , Only you know the details of decision implementation .
Module information hiding : The secret of the module ( Places that are easy to change ): Responsibilities assigned according to needs 、 Internal implementation mechanism .
【 Question type 】 For instance , Explain the degree of information hiding . The teaching material 222 page
【 Project practice 】 Coupling processing ?
Layered style : Only program calls and simple data transfer
Package design : Eliminate duplicate
to subcontract : Minimize the interface
Creator mode : No new coupling is added
Controller mode : relieve View And Logical Direct coupling ofCohesive processing ?
layered : The distribution of responsibilities among layers is highly cohesive , In layer subcontracting high cohesion
Information expert model
Controller and delegated control styleInformation hiding processing ?
Layering and subcontracting : Eliminate duplication of responsibilities 、 Minimize interfaces :View Independent ? The database connection is independent ?
Module information hiding : Module requirement allocation and interface definition
Class information hiding : Collaborative design , Interface definition
Change design ? Layered style 、RMI
The first 14 Chapter Object oriented modularity
14.1. Access coupling
14.1.1 Implicit coupling :Cascading Message Cascading call problem
- Avoid implicit coupling , Become explicitly coupled , Reduce coupling
- Use the method of delegation to solve , Delegate to a class to complete the business
14.2. Decoupling method
14.2.1. Programming to an interface
- Program to the required interface , Not just supported interfaces
- Design as agreed
- modular / Class contract : Required method / Methods provided
- Method contract : Prerequisite , Postcondition , Invariant
- precondition ( precondition): The conditions that a use case must meet when calling a method .
- Postcondition (postcondition): Implement the requirements that must be met when the method returns .
- side effect (side effects): Any other changes that the method may make to the object .
- In considering ( Non inherited ) The relationship between classes , On the one hand, the value is required to access the other party's interface , On the other hand, avoid implicit access .
14.2.2. Minimize the interface / Interface separation principle
Independent interfaces avoid unnecessary coupling
14.2.3. Dimitar's law
- In popular parlance
- You can play by yourself .(this)
- You can play with your own toys , But you can't take them apart ( Own member variables )
- You can play with the toys given to you .( Method )
- You can play with your own toys .( Self created objects )
- A more formal statement :
- Each unit can only have priority knowledge of other units , Just a unit that is closely related to the current unit
- Each unit can only talk to its friends , Don't talk to unfamiliar units
- Only talk to your direct friends
- Book p233
14.3. Inheritance coupling
- In the above various types of inheritance relationships , Modify the specifications 、 Modify implementation 、 Refined specifications are not acceptable .
- Extension is the best inheritance coupling
14.4. Decoupling method
14.4.1.liskov Substitution principle
This man writes quite clearly : Deep analysis of the seven principles of design patterns —— Richter's principle of substitution
- Subclasses can implement abstract methods in the parent class , however Can not rewrite ( Cover ) Non abstract methods of the parent class .
- When the subclass needs to overload the methods in the parent class , Formal parameters of subclass methods ( Enter the reference ) Than the input of the parent method The parameters are more relaxed ( Wider scope ).
- When overriding or implementing a parent method , Methodical The return value can be reduced , But you can't zoom in .
“ When redefining a method in a derived class , Only a weaker method can be used to replace its prerequisites , Instead, a stronger method is used to replace the post condition ” — B. Meyer,1988 year
Problem cases
Is a Square a Rectangle?
Rect r = new Rect();
setWidth = 4;
setHeight = 5;
assert(20 == getArea());
class Square extends Rect{
// Square invariant, height = width
setWidth(x) {
setHeight()=x;
}
setHeight(x) {
setWidth(x)
}
} // violate LSP?
The length and width of the square are the same , You don't have to type width and height Two Numbers . The condition of child analogy is stronger than that of parent , Multiple constraints . It indicates that the preconditions are too strong .
Penguin is a bird?
class Bird {
// has beak, wings,...
public: virtual void fly();
// Bird can fly
};
class Parrot : public Bird {
// Parrot is a bird
public: virtual void mimic();
// Can Repeat words...
};
class Penguin : public Bird {
public: void fly() {
error ("Penguins don’t fly!");
}
};
void PlayWithBird (Bird abird) {
abird.fly();
// OK if Parrot.
// if bird happens to be Penguin...OOOPS!!
}
penguin 、 Ostriches and kiwis are divided biologically , They belong to birds ; But from the perspective of class inheritance , Because they can't inherit “ bird ” The ability to fly , So they can't be defined as “ bird ” Subclasses of .
Class practice
The left side is bad , Because the preconditions are too strong , Ordinary doors will not alarm .
The right side is not good ,door There is no substitute for alarm
14.4.2. Combining alternative inheritance
- Combination over inheritance
- Use inheritance to achieve polymorphism
- Using delegates does not inherit reuse code !
Inherit / Combine Instance of a
- If there is a user who is Passenger It's also Agent
- Java Multiple inheritance not allowed
- A direct idea is a direct combination
- Person It holds Passenger、Agent, But it's strange for a single person at this time
Case 2
- Person hold Role,Passenger and Agent Implement abstract interfaces PersonRole
- Role It could be a List
Case three
class Object {
public: virtual void update() {};
virtual void draw() {};
virtual void collide(Object objects[]) {};
};
class Visible : public Object {
public:
virtual void draw() {
/* draw model at position of this object */ };
private: Model* model;
};
class Solid : public Object {
public:
virtual void collide(Object objects[]) {
/* check and react to collisions with objects */ };
};
class Movable : public Object {
public:
virtual void update() {
/* update position */ };
};
- problem : There are many objects in the game engine , Each of the three classes implements one of the methods
- Inherited three things but did only one ,Promise No Less Do not conform to the
- The interface should be disassembled into 3 individual
The improved scheme :
14.3. cohesion
- Cohesive classification reference textbook 237 page , Functional cohesion 、 informational cohesion 、 Process cohesion 、 Time converges 、 Logical cohesion 、 To gather by chance .
- Methods and properties are consistent
- Improve cohesion : Divide a class into three classes
- Abstract time
14.3.1. Method cohesion
- One type of method is general coupling
- All methods do their duty
- informational cohesion
- Relative function ( Functional cohesion )
- The ninth principle : The principle of single responsibility
14.4. Ways to improve cohesion
14.4.1. Principle of single responsibility (SRP)
“ A class has only one reason to change ”- Robert · Martin (Robert Martin)
- Relating to and deriving from cohesion , That is, the elements in the module should be functionally closely related
- The responsibility of the class to perform certain duties is also the cause of class changes
- A highly cohesive class is not only information cohesive , It should also be functionally cohesive .
Problem case 1
- The reason for the change :
- Business logic
- XML Format
- How to modify how to separate
- We will The responsibilities of the two parts are separated open
Case 2
- Calling and hanging up are two separate duties
Case three
- Geometer's Sketchpad :Draw and Area How to separate the calculations of
Case four :
- Solution : Set rectangle and graphic rectangle correspond to each other
14.5.Summary:Principles from Modularization The principle of modularity
- 《Global Variables Consider Harmful》 Global variables are considered harmful
- 《To be Explicit》 Make the code clearer
- 《Do not Repeat》 Avoid repetition
- 《Programming to Interface(Design by Contract)》 Interface oriented programming , Design according to the contract
- 《The Law of Demeter》 Dimitar's law
- 《Interface Segregation Principle(ISP)》 Interface separation principle
- 《Liskov Substitution Principle (LSP)》 Richter's principle of substitution :Request No More, Promise No Less
- 《Favor Composition Over Inheritance》 Choose combination instead of inheritance
- 《Single Responsibility Principle》 The principle of single responsibility
The first 15 Chapter Object oriented information hiding
15.1. The meaning of information hiding
Each module hides the implementation of important design decisions in this module , So that only each component of this module can know the specific details
Two common design decisions that need to be hidden
- demand ( The main secret of the module description ) With the implementation —— Expose external performance , Package the internal structure
- Implement mechanism change ( The secondary secret of the module description )—— Expose stable abstract interfaces , Encapsulate specific implementation details
Object oriented mechanism
- encapsulation : Responsibilities of the encapsulation class , Hide the realization of responsibilities + Expected changes
- abstract class ( Interface )/ Inherit ( Realization ): Abstract its interface , And hide its internal implementation
15.2. Class encapsulation
- The purpose is information hiding
- Encapsulation includes both data and behavior in a class , Separate External interface And Internal implementation .
- An interface is a visible part of a module : Describes the visible features exposed to the outside world in a class
- Implementations are hidden in modules : Hiding the implementation means that you can only operate within a class , Update data , It does not mean that the interface data is hidden .
- Initial view of encapsulation : The data ( internal structure ) Hidden in abstract data types
A new view ( Information hiding ): Hide anything : Data and behavior 、 Complex internal structure 、 Other objects 、 Subtype information 、 Potential changes - Encapsulate data and behavior : Unless ( Directly or indirectly ) To meet the needs ( Type requires ), Do not set the operation to public. Action required by type : In order to meet user tasks, it is necessary to expose methods of objects in external collaboration , For example, the 4 Operations ( Belongs to the latter object , To meet the task of calculating the total price of goods )
Unless ( Directly or indirectly ) To meet the needs ( Type requires ), Do not define for attributes getX Methods and setX Method , Don't define it as public. For example, in the previous example getPrice() - Packaging structure : Don't expose complex internal data structures , Experience has shown that complex data structures are prone to modification . For example, internal use is exposed List data structure .
improvement :Iterator Pattern ( This problem may occur in all operations involving collection types ) - Encapsulate other objects : entrust Instead of providing references to other objects that you own , perhaps new A new object returns . Unless Client Object already has a reference to that other object , At this time, returning its reference will not increase the complexity of the overall design, which can ensure Sales Just connect SalesList, No association is required SalesLineItem and Commodity; In terms of the whole design ,Sales You don't need to know SalesList What's in it is SalesLineItem Set , There is no need to know SalesLineItem Used Commodity type .
- Encapsulate subclasses (LSP: Subclasses must be able to replace their base classes )
- Encapsulate potential changes : Identify parts of the application that may change , Separate it from unchanging content
Encapsulate potentially changing parts that stand alone , In this way, it can be modified or extended without affecting the unchanged part ( DIP and OCP)
15.3. Opening and closing principle OCP
Open to expansion , Closed to modification
A violation of the OCP Typical symbol of principle : There is switch perhaps if-else
Branching adds complexity to the program , It is easy to make new mistakes when modifying ( special case : establish )
It's the kind with expansion , such as : oriented os And face andriod, At this time, we need to separate them with factory mode , To facilitate extension ( There may be other aspects mac wait ).
15.4. The principle of Dependence Inversion DIP
( Closely integrated with the factory , solve new The creation of )
I. High level modules should not rely on lower level modules , Both should rely on abstraction
II. Abstraction should not depend on details , Details should depend on abstraction
Using abstract classes ( Inherit ) Mechanism inversion dependency
Example :A Depend on B:B Not an abstract class , therefore A Dependent on specific , Not abstract , If changes are needed B act , Will affect A
Add abstract class BI, Give Way B Realization ( Inherit )BI:A Depend on BI,B Depend on BI,BI Abstract class , So it depends on abstraction ,BI More stable , If B change , You can do this by BI Extend the new implementation ( subtypes ) To satisfy
The title is similar to :
The first 16 Chapter Design patterns
16.1. How to achieve modifiability 、 Extensibility 、 flexibility
The teaching material 263 page
need Separation of interface and implementation : Through the interface and the class that implements the interface ; Inherit the parent class through subclasses
Be careful : Inheritance relationships (A+B) May reduce flexibility , Because the change of the parent class interface will affect the children , At this time, it can be solved through the combination relationship .
utilize Abstract class mechanism Realize modifiability and extensibility : As long as the interface of the method remains unchanged , The implementation code of the method is relatively easy to modify , There will be no chain reaction . Simply modify the code to create a new class , It is quite easy to expand new requirements ( There is no need to modify a lot of code related to class method calls .
utilize Delegation mechanism Achieve flexibility : The defects of inheritance : Once an object is created , Its type cannot be changed , This makes it impossible to achieve flexibility by simply using inheritance mechanism ( Dynamic change of type ). Use combination ( entrust ) Mechanisms can solve this problem
16.2 Design patterns and Strategy Pairing
- The strategy pattern : Reduce coupling 、 Dependency inversion .
- Abstract factory pattern : Abstract responsibilities 、 Interface reuse .
- singleton pattern : Information hiding 、 Abstract responsibilities .
- Iterator pattern : Reduce coupling 、 Dependency inversion .
16.3. The strategy pattern
Reduce coupling , Comply with opening and closing principle , extensible ; It also conforms to the principle of dependence inversion , Concrete depends on abstraction .
test: adopt new Parameter NEW employee, from set Function to set specific strategies .
Context:employee, Contains employee Personal attributes ,set Strategy , Call interface functions to implement strategies .
Strategy: Including the interface Strategy, And implementation class concrete Strategy,Context After setting the specific strategy , Implement specific strategies by calling interfaces .
Simplified template :
/**
* The strategy pattern
* When a function can be implemented using multiple algorithms or methods
* If you choose business code if Hard code under equal split statements , When similar scenes appear many times, many places will be changed if they are modified , Violates the open close principle
* Based on opening and closing , At this time, I will think of these ' Strategy ' Methods to carry out unified management , Use it directly new This management class , Just call the corresponding method
* In order to unify the management of various strategies and methods ( Such as adding some log printing and other operations ), Abstract a context class context Unified management of it
*/
public class StrategyPattern {
public static void main(String[] args) {
Context context = new Context();// New context
Strategy addStrategy = new AddStrategy();// Add specific strategies
context.setStrategy(addStrategy);// Set specific policies
context.invoke(1, 2);// operation
Strategy minusStrategy = new MinusStrategy();
context.setStrategy(minusStrategy);
context.invoke(4, 2);
}
}
// An abstract strategy is an interface
interface Strategy {
// The strategy inside is left to the specific strategy implementation
void doStrategy(int a, int b);
}
// Specific strategies 1, Realization +
class AddStrategy implements Strategy {
@Override
public void doStrategy(int a, int b) {
System.out.println(a + b);
}
}
// Specific strategies 2, Realization -
class MinusStrategy implements Strategy {
@Override
public void doStrategy(int a, int b) {
System.out.println(a - b);
}
}
// Context class , Manage policy objects and some additional common logic
class Context {
private Strategy strategy;
// Get specific strategies
public Strategy getStrategy() {
return strategy;
}
// Set specific policies
public void setStrategy(Strategy strategy) {
this.strategy = strategy;
}
// According to the specific strategy , function
void invoke(int a, int b) {
System.out.println("Context invoke start");
strategy.doStrategy(a, b);
System.out.println("Context invoke done");
}
}
16.4. Factory mode
Abstract responsibilities , Interface reuse
Also simplify the template :
/** Digital abstract products */
public interface Digit {
public void display();
}
/** Black numbers , Act as a specific product */
public class BlackDigit implements Digit {
public void display(){
System.out.println(" Display black numbers ");
}
}
/** Red numbers , Act as a specific product */
public class RedDigit implements Digit {
public void display(){
System.out.println(" Display red numbers ");
}
}
/** Alphabetic Abstract products */
public interface Letter {
public void display();
}
/** Black letters , Act as a specific product */
public class BlackLetter implements Letter {
public void display(){
System.out.println(" Show black letters ");
}
}
/**Summer Textbox class , Act as a specific product */
public class RedLetter implements Letter {
public void display(){
System.out.println(" Show red parent and child ");
}
}
/** Symbolic Abstract products */
public interface Mark {
public void display();
}
/** Black symbol class , Act as a specific product */
public class BlackMark implements Mark {
public void display(){
System.out.println(" Show black symbol ");
}
}
/** Red symbol class , Act as a specific product */
public class RedMark implements Mark {
public void display(){
System.out.println(" Show red symbol ");
}
}
/** Font color abstract factory */
public interface ColourFactory {
public Digit createDigit();
public Letter createLetter();
public Mark createMark();
}
/** Black specific factory */
public class BlackColourFactory implements ColourFactory {
public Digit createDigit(){
return new BlackDigit();
}
public Letter createLetter(){
return new BlackLetter();
}
public Mark createMark(){
return new BlackMark();
}
}
/** Red specific factory */
public class RedColourFactory implements ColourFactory {
public Digit createDigit(){
return new RedDigit();
}
public Letter createLetter(){
return new RedLetter();
}
public Mark createMark(){
return new RedMark();
}
}
/** Client test class */
public class Client{
public static void main(String args[]){
// Use an abstraction layer to define
ColourFactory factory;
Digit dt;
Letter lt;
Mark mk;
//factory=(SkinFactory)XMLUtil.getBean();
// For the principle of opening and closing , You can use reflection mechanism and xml Get the interface class you want to use
factory = new RedColourFactory();// If you want to change the color, you can modify it here
dt = factory.createDigit();
lt = factory.createLetter();
mk = factory.createMark();
dt.display();
lt.display();
mk.display();
}
}
16.5. singleton pattern
Abstract responsibilities , Hide the implementation of singleton creation . There is only one implementation of the specific factory .
16.6. Iterator pattern
边栏推荐
- Data analysis - Thinking foreshadowing
- 【原创】程序员团队管理的核心是什么?
- UVA – 11637 garbage remembering exam (combination + possibility)
- Rasa 3.x 学习系列-Rasa 3.2.1 新版本发布
- Solution to the packaging problem of asyncsocket long connecting rod
- Leetcode sword finger offer brush questions - day 21
- GFS分布式文件系統
- Dynamic memory management (malloc/calloc/realloc)
- Scala concurrent programming (II) akka
- (4) UART application design and simulation verification 2 - TX module design (stateless machine)
猜你喜欢
Go语言实现原理——锁实现原理
Rasa 3. X learning series -rasa x Community Edition (Free Edition) changes
rsync远程同步
Dynamic planning: robbing families and houses
21.PWM应用编程
14种神笔记方法,只需选择1招,让你的学习和工作效率提高100倍!
Brushless drive design -- on MOS drive circuit
TVS管 与 稳压二极管参数对比
2: Chapter 1: understanding JVM specification 1: introduction to JVM;
《牛客刷verilog》Part III Verilog企业真题
随机推荐
保研笔记二 软件工程与计算卷二(13-16章)
Multi sensor fusion of imu/ optical mouse / wheel encoder (nonlinear Kalman filter)
Southeast Asia e-commerce guide, how do sellers layout the Southeast Asia market?
6-axis and 9-axis IMU attitude estimation
Summary of binary tree recursive routines
Redis高可用——主从复制、哨兵模式、集群
Multi view 3D reconstruction
Switching power supply buck circuit CCM and DCM working mode
idea 连接mysql ,直接贴配置文件的url 比较方便
golang代码检查工具
Spire Office 7.5.4 for NET
21.PWM应用编程
Hcip course notes-16 VLAN, three-tier architecture, MPLS virtual private line configuration
Xinyuan & Lichuang EDA training camp - brushless motor drive
Solution to the packaging problem of asyncsocket long connecting rod
MySQL (2) -- simple query, conditional query
[Yu Yue education] NC machining technology reference materials of Shaanxi University of science and technology
Go language implementation principle -- lock implementation principle
It is proved that POJ 1014 module is optimized and pruned, and some recursion is wrong
2022.6.20-6.26 AI industry weekly (issue 103): new little life