Object-oriented, server architecture, and design patterns

Source: Internet
Author: User

Reprinted from: http://hi.baidu.com/wind_stay/blog/item/fe9db22c5b44b03e359bf75b.html

 

Object-oriented, server architecture, and design patterns
And seek out your friends.
Original: Lu yueqiang copyright statement: all belongs to Lu yueqiang, and any transfer and reference must specify the source
Primary to internal
N1 Server Architecture
Design Pattern of N 2, application of object-oriented in server development
Refer:
Network Infrastructure: Ace
Efficient concurrent server structure: Apache (high session independence)
Special Application Server: Darwin Streaming Media Server,
1. Server Architecture
1.1 iterations vs concurrency vs Hybrid
Iteration: the processing time for each event is short and simple. Session processing is not complex, and can be divided into multiple transient steps and processed separately
Concurrency: the session is complex. The blocking in the session is uncertain, and the session context is complex. For example, to process a transit session, receive a read request, then interact with the database, then interact with the encryptor, then submit a request to the server, read the server response, and then encrypt the machine interaction, database, then respond to the client. Multithreading is recommended.
HYBRID: iterative processing at ordinary times, concurrent processing of high consumption requests
1.2 multithreading VS Multi-Process
N multithreading: high efficiency and low resource occupation. Shared address space, with great impact between threads
N multi-process: low efficiency and high resource occupation. But it is safe and stable.
N Apache is a multi-threaded process that integrates efficiency and security.
1.3 concurrent Classification
N 1.3.1 each connection pthread_create once
A thread is enabled for processing each event and the processing thread exits. In fact, this mode is quite efficient in some systems, that is, the platform that uses native threads.
This mode is widely used in a few systems with low pressure. And easy to compile.
1.3.2 pre-created Thread Pool Mode
N 1.3.2.1 pre-created semi-synchronous/semi-asynchronous (producer/consumer) Mode
The main thread (producer thread) listens to the event and then drops the event and parameter in a queue. Consumer threads read queue data for processing
Generally, the main thread processes I/O events, parses them, then drops data in the queue, and then the consumer reads the data for application logic processing. Of course, the main thread can also discard the handle directly into the queue without handling I/O events, so that consumers can process I/O and application logic.
Advantage: simplified programming separates low-layer asynchronous I/O from high-level synchronous application services without lowering the performance of low-layer services. Centralized inter-layer communication. In addition, suitable for interactive sessions
Disadvantage: data needs to be transmitted between threads. Therefore, dynamic memory allocation, data copying, and context switching bring about overhead. High-level services cannot benefit from the efficiency of underlying asynchronous services.
Scheduling of the N thread pool: You can use the OS semaphore or conditional variable, or you can manage the thread object by yourself, and then the program activates a specific thread.
This mode is widely used in many systems.
Semi-synchronous semi-asynchronous Block Diagram
1.3.2.2 pre-create the frontend/followers Mode
N each time a thread leader is allowed to wait for the event source to close. At the same time, other threads wait in line to become leaders. After the leader detects the event, it immediately transfers it to follower and promotes a follower to leader. Then, it directly processes the event and is in the processer role. After the event is processed, it becomes a follower.
Disadvantages: complexity and lack of flexibility
Advantage: enhances the high-speed cache similarity of CPU and eliminates dynamic memory allocation and data exchange between threads.
Notes
N determines the handle type. UDP concurrency handle. TCP socket is the iteration handle.
N determines the type of the handle set. Waitformultipleobjects () is concurrent, while select is iterative.
N event separation and processing, role conversion. The underlying operating system can queue events internally until there is a leader
N is widely used in OLAP systems.
1.4 Memory Pool Management
N overload new/delete
For example, in my ctcpwrrdsocket, the new function is reloaded to implement the static memory pool.
N refer to the STL configurator allocator to create a dynamic cmemory class. This job has not been done yet
1.5 Server
N Configuration File Processing
Apache's configuration file processing system is worth exploring. In my framework, there is a simple class. We recommend that you inherit a configuration that supports XML format.
N log processing
(Currently, my log system is implemented by the C library function. You can also use the <operator if you are used to it. Note that stream operations such as Endl, Hex, and showbase are actually functions. I have not tried any operation with parameters)
N border processing socket (class diagram in the package mode Section)
N event separation select epoll_wait (class chart in the package mode Section)
N thread pool (class chart at the end)
N application logic processing
N some subsystems of the server can be dynamically loaded (ACE and Apache)
2 object-oriented
2.1 Design Method: Object-oriented vs process-oriented
The most important requirement of a program is to be able to meet the needs and run well. Both object-oriented and process can be well satisfied.
Misunderstanding: the software designed by the object-oriented method must be of higher quality than the process-oriented software.
Misunderstanding: as long as you learn VC ++ well, you will be able to master the object-oriented design method.
Of course, in the future, we hope to quickly build a new system with high quality. In this way, the software's expansion and maintainability are quite required. At this time, the object-oriented design method is very popular. The process-oriented approach is difficult.
Misunderstanding: As long as a class is used (some are only classes, but not even inheritance, not to mention polymorphism), It Is Object-Oriented.
In fact, the class is only based on object programming.
N process orientation is generally divided into functions according to functions. In this way, great coupling (external variables and function coupling) exists in a very large software system, and it is difficult to manage, and expansion and maintainability are not high. It is a headache to manage variable names and function names. Objects in the real world are often the combination of attributes and actions. Therefore, process-oriented systems that focus on functional operations and do not have high requirements for expansion are suitable.
N Rational Unified Process (RUP): a process of continuous repetition, starting from, refining, building, and handover. Agile development (XP): in fact, it is also down generation. The object technology is very important here. Otherwise, the original code cannot be downgraded and must be overwritten. The lower generation of the previous cycle only verifies the feasibility.
N rup and XP are not implemented in a few weeks of training.
2.2 object-oriented principles
N open/closed principle: a module is open to expansion and closed to modification.
N full replacement principle: the derived class can completely replace the base class.
N non-circular dependency principle: Avoid circular dependency between packages.
N Dependency inversion principle: dependency abstraction, instead of dependency and representativeness
N preferentially uses aggregation instead of inheritance.
N code writing: the code style should be uniform and concise
Explanation of the principle of opening/closing and the principle of dependency inversion
2.3 Object-Oriented Design
2.3.1 class granularity: commonalities vs individuality
N logs: logs are classified by type. Based on the requirements, logs can be remotely stored locally, rolled by entry, with a prefix without a prefix. Remote users can also use tcp udp. All classes except UDP can be inherited to implement a thread security. In fact, you can try again. In this way, the class chart is very cumbersome.
N inheritance granularity and avoidance of users' branch code conflicts
N use aggregation to reduce the types of classes (when the differences are large)
If n is used, the (attribute) Switch quantity is reduced.
Measure the granularity of commonality vs individuality
2.3.2 class Responsibility Assignment
N General Responsibility Assignment software model (GRASP): a summary and summary of the design principles.
N 9 Responsibility Assignment modes: Expert creators low Coupling High Cohesion controllers polymorphism pure fictitious intermediaries do not speak to strangers
2.3.2.1 do not speak to strangers
Class cinerdatawkthread
{
PRIVATE:
Creator * m_ptreactor;
Public:
Threadfunc (void)
{
If (false = m_bisstatic)
N {
N if (! Setayncancel ())
N {return-1 ;}
N}
N while (1)
N {
N wait ();
N // speaking to a stranger cobserver, error
N m_ptreactor-> getobserver ()-> eventprocess (& m_teventpara );
N // only talks to m_ptreactor. m_ptreactor is responsible for talking to cobserver. Correct
N m_ptreactor-> eventpolicy ();
N}
N return 0;
N}
N}
2.3.2.2 experts: Consistent with encapsulation features
M_tqueuetdata is exposed in two classes, leading to Lock unlock code everywhere.
According to the principle of experts, a separate class should be made for them to fulfill this responsibility.
2.4 design pattern: the path of change vs the eternal beauty
N mode: each mode describes a problem that occurs constantly in our environment and describes the core solution to the problem, so that you can use this solution multiple times, you do not have to try again.
Composition of the N mode: including the name, solution, and usage result.
The essence of the N mode: 1 adapts to changes 2 programming for interfaces, rather than implementing programming (in fact, virtual + inheritance) 3 prioritize aggregation rather than inheritance
2.4.1 classification of Modes
N architecture mode: 1.1 layered mode 1.2 pipe and filter 1.3 blackboard 2.1 C/S P2P B/S 3. MVC
N design mode:
N mode: Factory method, adapter, template method, Interpreter
N Object Mode: Abstract Factory, prototype mode, single piece, bridge composite decoration appearance enjoy meta PROXY command drop proxy intermediary observer responsibility chain strategy
2.4.2 package mode: interface 1 vs. detail exposed
N is also called an adapter)
N definition: converts an interface of a class or a group of Apis into another interface that the user wants.
The n standard can be implemented by inheritance or aggregation, and aggregation is recommended.
2.4.3 Bridge Mode
When n an abstraction has multiple implementations, inheritance and coordination are usually used. An abstract class defines an interface. The specific subclass is implemented in different ways. This method is sometimes not flexible enough. The Inheritance Mechanism binds the abstract and implementation parts together.
N. I feel like I have changed the list into a permutation and combination, and I have modified all the relevant changes at a time (for example, 9 digits and 10 digits make up 90 double digits, so I don't need to mention 90. I used 10 numbers. It turns out to be 10-19, and now it is 20-29. It only takes 1 to 2)
N intention: separate abstract parts and implemented parts so that they can change independently
2.5 observer mode: indirect dependency vs direct dependency
N. Who or when to trigger the update, delete the target, observe multiple targets, and push-pull the parameters.
N variation of the observer in the server: display the change of the reactor mode of the specified interest
Direct dependency becomes indirect dependency
2.6 single-piece mode: Implicit global vs explicit global
N no need to release memory
N mode introduction:
N global variable headache
N self-built multi-part Mode
Class
{
Public:
Static A * instance ();
~ A ();
Protected:
A ();
PRIVATE:
Static A * m_pthis;
}
A * A: m_pthis = NULL;
A * A: instance ()
{
If (null = m_pthis)
{M_pthis = new A (); Return m_pthis ;}
Else {return m_pthis ;}
}
Self-built multi-part Mode
Class canonymsem
{
Public:
Canonymsem ();
~ Canonymsem ();
Static canonymsem * getfirstsingleton (void );
Protected:
Static canonymsem * m_pfirst;
Sem_t m_tsem;
};
Canonymsem * canonymsem: m_pfirst = NULL;
Canonymsem * canonymsem: getfirstsingleton (void)
{
If (null = m_pfirst)
{
M_pfirst = new canonymsem ();
Return m_pfirst;
}
Else {return m_pfirst ;}
}
2.7 template method: Dependency inversion vs positive dependency
Hollywood principles
Class cappserver
{
Public:
Void run (void)
{
Daemon ();
Signalinit ();
Realrun ();
}
Protected:
Int daemon ();
Int signalinit ();
Virtual int realrun ()
{Cout <"Hello, in cappserver: realrun ()" <Endl ;}
}
Class cmyserver: Public cappserver
{
Protected:
Int realrun ()
{Cout <"Hello, in cmyserver: realrun ()" <Endl ;}
}
Main ()
{
Cappserver * pmyapp = new cmyserver;
Pmyapp-> Run ();
}
3. My Server framework class diagram
Thank you for your support. If you have any suggestions, please send an email to the following mailbox:

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.