"Enterprise Application Architecture mode Chinese Version" study notes (GO)

Source: Internet
Author: User

This book introduces some basic knowledge of enterprise application development, such as layered architecture, web representation, business logic, database mapping, concurrency, session, distribution strategy, etc. The design patterns (including some common design patterns GOF23 and the newly created design patterns in this book) are described in detail using scenarios, solutions, and UML. Find out what these patterns are in the book, What they solve, and how they solve the problem. This way, if you encounter a similar problem, you can find the corresponding pattern from the book. You can save costs, shorten project cycle times, and avoid risks to ensure the project is completed perfectly.

一、三个 Basic level: Presentation layer, domain layer, data source layer

Level

Duty

Presentation Layer

Provide services that display information (such as in Windows or HTML pages, handling user requests (mouse clicks, keystrokes, etc.), HTTP requests, command line invocation, batch API)

Domain Layer

Logic, the real core of the system

Data source Layer

communicates with databases, message systems, transaction managers, and other packages

On the principle of universality of dependency: the domain layer and the data source layer should never depend on the presentation layer.

Once the processing node is selected, the next step is to keep all of the code within a single process (either on the same node or on multiple nodes in the cluster). Do not put hierarchies in multiple processes unless you have to. Because doing so will not only lose performance, but also increase complexity, because you must add patterns like the following, such as remote appearances and data transfer objects.

Complex supercharger: Distribution, explicit multithreading, paradigm differences, multiplatform development, and extreme performance requirements (e.g. 100 transactions per second or more).

Ii. Domain Logic

The organization of domain logic can be divided into three main modes: Transaction script, domain model, and table module.

The difference between the three:

A transactional script is a process that controls the execution of a series of action logic.

A domain model is no longer a process to control the logic of a user's actions, but rather a part of the relevant logic for each object. These objects can be seen as different parts of the domain.

The table module has only one public contract class instance, and the domain model has a corresponding instance of the contract class for each contract in the database.

Third, mapping to relational database

When using the domain model, its reading should read the associated object as well. For example, to read a contract, the products involved in the contract and the objects of the ordering vendor should be loaded into memory. By the time in order to avoid these unnecessary joint reads, we can use the "lazy load" model.

When reading data, performance problems may become more prominent. This leads to several rules of thumb.

1), query as many records as possible, do not query one record at a time, and then make multiple queries. You can query multiple related records at one time, such as using a federated query. Or use more than one SQL statement.

2) Avoid multiple access to the database by using a join, so that you can return multiple tables at once. A portal can be made to allow the entry to complete a one-time read of the relevant data.

3) The database is optimized. DBA to tune the database.

When mapping to a relational database, you typically encounter three scenarios:

1) Choose your own database solution.

2) have to map to an existing database schema, this scheme cannot be changed.

3) have to map to an existing database schema, but this scenario can be considered for change.

The simplest case is to choose your own database schema without accommodating the complexity of the domain logic. When a database schema already exists, you should build the domain model and include the data Mapper to save the data to the existing database.

Iv. concurrency

Concurrency issues: Update loss and inconsistent reads.

Concurrency issues, a variety of different solutions have been proposed. For enterprise applications, there are two very important solutions: one is isolation and the other is invariance.

Isolation is the partitioning of data so that each piece of data can be accessed by an execution unit. such as file locks.

Immutability is the identification of unchanging data, rather than the concurrency of the data, which is widely shared.

What happens when there are some mutable data that cannot be isolated? In general, we can use two forms of concurrency control strategy: Optimistic concurrency control and pessimistic concurrency control.

If you think of optimistic locking as a conflict detection, then pessimistic locking is about conflict avoidance.

If Martin and David were to edit the customer file at the same time. With the optimistic locking strategy, all two of them can get a copy of the file and be free to edit the file. Assuming David is the first to finish the job, he can update his changes without any difficulty. However, when Martin wants to commit his changes, the concurrency control strategy will begin to work. The source control system detects a conflict between Martin's changes and David's changes, rejecting Martin's submission and the Martin's responsibility to indicate how to deal with the situation. If a pessimistic lock policy is used, no one else can edit the file as long as someone takes it out first. So, if Martin took out the file first, David would only be able to work on the file after Martin had completed the task and submitted it.

Multiple technologies to handle deadlocks: one is to use software to detect the occurrence of deadlocks. The other is to add a time limit to each lock, once the time limit is reached, the added will be invalidated, the work will be lost.

Software transactions are often described using acid properties.

Atomicity (atomicity): In a transaction, each step of an action sequence must either be successful or all of the work will be rolled back. Partial completion is not a transactional concept.

Consistency (consistency): At the beginning and completion of a transaction, the resources of the system must be in a consistent, non-destructive state.

Isolation (Isolation): A transaction is not visible to all other transactions until it is successfully committed.

Persistence (Durability): Any result of a committed transaction must be permanent, that is, "can be saved in the event of any crash".

Most enterprise applications involve transactions in the database, but there are a lot of things to do with transaction control, such as Message Queuing, printers, and ATMs. To handle the maximum throughput, modern transaction processing systems are designed to keep transactions as short as possible, to keep transactions from spanning multiple requests, and to open transactions as late as possible.

Five, distribution strategy

The main reason that the method of distributing according to class model is not feasible is related to the basic characteristics of computer. Process calls within a process are very fast. Process calls between two opposing processes are slowed by an order of magnitude. The process of running between machines is one or two orders of magnitude slower, depending on the network topology.

The local interface is preferably a fine-grained interface. However, fine granularity is not well used in remote calls. Distributed object Design The first law: Do not distribute the use of objects, in most cases, the use of clustered systems.

Vi. some recommendations on specific technologies

1. Java and EE

The value of Enterprise Java Beans (EJBS) is the biggest controversy in the Java world. But to build a good Java EE reference, you don't actually need ejbs. Using Pojo (plain Java objects) and JDBC can also accomplish this task. The design choice of the Java EE is different from the pattern used, and it is also restricted by the domain logic.

2,. NET

In. NET, Visual Studio, and Microsoft World applications, where the deciding mode is the table module: NET aggressively promotes Web services, but I don't use Web services inside an application, but just like in Java, using them as a presentation layer that allows application integration.

2. Stored Procedures

3. Web Services

WEB Services make reuse a reality and eventually lead to the disappearance of system integrators.

4. Other layers

Vii. patterns

Domain Logic mode

1. Transactional scripting: Use procedures to organize business logic, each of which processes individual requests from the presentation layer.

Where a transactional script is placed will depend on how you organize your software hierarchy, which may be in Server Pages, CGI scripts, and distributed session objects. I like to detach the transaction script as much as possible. At a minimum, they should be placed in separate subroutines, and a better approach would be to put them in classes separate from other classes that handle the presentation and data source layers. In addition, never let the transactional script invoke any representation logic, which makes it easy to modify the code and test the transaction script.

There are two ways to organize transactional scripts into classes. One is to put multiple transactional scripts in a class, each of which organizes related transactional scripts around a topic. Another approach is to have a class for each transaction script, which completes the message passing through the command pattern.

2. Domain Model: An object pattern that incorporates the fields of behavior and data.

Domain model According to its complexity, can be divided into: simple domain model and complex domain model. Simple domain models such as "activity records" can be used to deal with simpler systems of domain logic. Complex domain logic requires a complex domain model.

3. Table module: an instance of the business logic that processes all the behaviors in a database table or view.

The table module organizes domain logic with a table in a class-corresponding database, and uses a single class instance to contain the various operating procedures that will be performed on the data. The main difference between it and domain logic is that if you have many orders, the domain model has an object for each order, and the table module uses only one object to process all orders.

4. Service layer: Define application boundaries through a service layer, establish a set of available operations in the service layer, and coordinate the response of the application within each operation.

Data source schema mode

1. Table data Entry: an object that acts as a database table access portal. One instance handles all rows in the table.

The table data entry contains all the SQL used for a single table or view, such as SELECT, INSERT, UPDATE, Delete, and so on. Other code calls its methods to implement all interactions with the database.

2. Row data entry: an object that acts as a single record entry in the data source, one instance per line.

3. Activity record: An object that wraps a row in a database table or view, encapsulates the database access, and adds domain logic to the data.

4. Data mapper: A mapper layer that moves data between objects and databases when they are kept separate from each other.

A data mapper is a software layer that separates memory objects from the database. Its responsibility is to pass data between the memory object and the database and keep them separate from each other. With a data mapper, memory objects don't even need to know the existence of a database, they don't require SQL interface code, and of course they don't need to know the database schema. Because the data mapper is a form of a mapper, the data mapper itself is not perceived at all by the domain layer.

Object-Relational behavior pattern

1. Unit of work: Maintain a list of objects affected by the business and coordinate the resolution of changing writes and concurrency issues.

A work cell is an object that records these changes. As soon as you start doing something that might affect your database, create a unit of work to record these changes. This unit of work is notified whenever an object is created, altered, or deleted.

The key to a work cell is that it decides what to do at the time of submission. It opens a transaction, does all the concurrency checks (using pessimistic offline locks and optimistic offline locks), and writes the changes to the database. Developers do not have to explicitly invoke the database Update method at all. This way, they do not have to record what they have modified or how referential integrity can affect their sequence of operations without worrying about it.

2. Identity mapping: Ensure that each object is loaded only once, by saving each loaded object in the map. When you want to access objects, look for them by mapping.

3. Lazy loading: An object that does not contain all the data it needs, but knows how to get the data.

Four ways to implement lazy loading: lazy initialization, virtual proxy, value-hold, ghosting.

Object-Relational structure pattern

1. Identity domain: A database identity domain in object memory in order to maintain identities between memory objects and database rows.

The data row is distinguished by a primary key in the database, however, the memory object does not require such a key, so that the object system can guarantee the correct identity (in C + + directly with the original memory location).

2. Foreign KEY Mapping: Mapping the association between objects to foreign key references between tables.

3. Association table Mapping: Saves the association as a table with a foreign key pointing to a table (about linked).

4. Dependency mapping: Let a partial class of a class perform database mapping.

5. Embedded value: Maps an object to a number of fields in another object table.

6. Serialize LOB: Save an object graph by serializing multiple objects into a large object (LOB) and store them in a database field.

7. Single-Table inheritance: The inheritance hierarchy of a class is represented as a single table, and the columns in the table represent all the fields in the different classes.

8. Class Table Inheritance: Each class corresponds to a table to represent the class's inheritance hierarchy.

9, the concrete table inherits: Each concrete class corresponds to a table to represent the class inheritance hierarchy.

Object-Relational metadata mapping pattern

1. Metadata mapping: Maintain relational-object mapping details in metadata.

Metadata mapping enables developers to define mappings in a simple tabular format that can be handled by common code, allowing for the details of reading, inserting, and updating data. The most important decision to use metadata mapping is how to represent the information in the metadata based on the running code. There are two main ways to do this: code generation and reflection programming.

2. Query object: The object that describes the database query once.

3. Resource pool: The coordination domain and the data mapping layer, using a collection-like interface to access domain objects.

Web Presentation mode

1. Model-View-Controller (MVC): Divide the user interface into three different roles.

2. Page Controller: The object that processes the request for a specific page or action on the Web site.

3. Front-End controller: The controller that handles all requests for a Web site.

4. Template view: Send messages to HTML by embedding tags in HTML also polygons.

5. Conversion view: A view that processes domain data one item at a-and converts them to HTML.

6. Two-step view: Convert domain data to HTML in two steps. The first step is to form some kind of logical page; The second step is to convert these logical pages into HTML pages.

7. Application controller: A centralized control point to handle screen navigation and application flow.

Distribution mode

1. Remote appearance: Provides coarse-grained appearance for fine-grained objects to improve efficiency on the network.

2. Data Transfer object: an object that transmits data between processes in order to reduce the number of method calls.

Serialization of data

Offline concurrency mode

1. Optimistic offline Lock: Prevents conflicts in concurrent business transactions through conflict detection and transaction rollback.

2. Pessimistic offline Lock: Only one business transaction is allowed to access data at a time to prevent conflicts in concurrent business transactions.

3. Coarse-grained Lock: Locks a set of related objects with a lock.

4. Implied lock: Allows the frame or layer super-type code to acquire an offline lock.

Session state Mode

Includes client session state, server session state, and database session state.

Data transfer objects are typically used to transfer the information. Data transfer objects can be serialized on the network, so even very complex information can be transmitted.

Client session state: The session state remains on the client. The client session state has some advantages. In particular, stateless server objects are supported, which improves maximum cluster performance and fault-tolerant recovery. Of course, if the customer crashes, all of its session data is lost, but the user usually thinks it's reasonable. For security issues, the data being transmitted is encrypted.

Customer data transfer: Customers also need to store data. Applications for big customers can be stored using their own data structures. If you use HTML, the situation is more complicated. There are generally three ways to do this: URL parameters, hidden fields for forms, and cookies.

Server session state: Stores the session state in serialized form on the server side.

One of the simplest methods in a server session is to put session data in the application server's memory. Session data can be stored in a memory-mapped table with the session ID as the key identifier. Only the client is given the session ID, and the server can remove the session data from the mapping table. This approach assumes that the application server has sufficient memory processing and that there is only one application server and no cluster-if the application server crashes, all session data is lost without a trace.

The solution is to serialize the server session state to the database, with a table with a key value for the session ID, which requires a serialized lob to hold the serialized session state. Also deal with obsolete sessions, especially in a customer-facing application. One approach is to use a monitoring process to check for and delete expired sessions, but this can result in many connections to the session table. Kai Yu provides a good way for him to use: divide the session table into 12 segments, rotate every two hours, and first delete all the data in the oldest segment of the time, and put all the new data into that segment. While this will force the session to be removed for more than 24 hours, there is really no need to worry about such a rare situation.

Implementation examples:

Java implements the most common server session state technology using HTTP sessions or using stateful session beans.

An HTTP session is an easy way for a Web server to save session state.

Using a stateful session bean, it requires an EJB server. The EJB container is responsible for persistent and passivation processing, so it is easy to implement.

。 NET implementation of server session state can be easily implemented using the built-in session State feature. By default, the. NET to place session state within the server process. can also be accessed through the State service, which can be locally or remotely. If you use the Remote State service, you can still use the original session data after restarting the Web server. It is not necessary to modify the application by specifying whether to use in-process or state services in the configuration file.

The state of a database session is to save session data to the database as committed data.

Basic mode

1. Ingress: An object that encapsulates external or resource access.

In fact, this is a very simple wrapper pattern. Encapsulates external resources, creates a simple API, and uses portals to transfer calls to the API to external resources.

2, Mapper: The object that establishes communication between two independent objects.

Mappers typically require data exchange between layers and layers. Once this data exchange is activated, the way it works is obvious. The difficulty with using the Mapper is how it is activated, so you cannot call it directly on either side of the mapped subsystem. Sometimes a third-party subsystem can be used to complete the mapping and invoke the mapper. Another alternative is to have the mapper become an observer for a subsystem. By monitoring the events that occur in the subsystem, the mapper can be called.

3. Layer Super Type: A type acts as a super type for all types in a layer.

All objects in a layer have some methods, but you do not want these methods to be duplicated multiple times in the system to produce redundant code. At this point you can move these behaviors to a common layer super type.

4. Separating interface

The interface is defined in one package, and the other is implemented in a package separate from the package.

5. Registration Form

A well-known object that other objects can use to find common objects and services.

6. Value object: A small and simple object, such as a currency or a date range, that is not judged by the identity ID.

In objects consisting of multiple types of objects, it is useful to differentiate between reference objects and value objects. The value objects are usually smaller in size; they are similar to the original types in many non-purely object-oriented programming languages. Generally, we tend to think of a value object as a small object, such as a currency object or a Date object, whereas a reference object is a large object, such as an order or a customer.

7. Currency: Represents a currency value

Object-oriented programming allows you to solve problems such as currency and amount (decimal point) by creating a currency class that handles currency. Surprisingly, there is no mainstream class library available for this class.

Create a currency class in which you save amounts and currencies, and you can save amounts as integers or fixed-point decimals.

8. Special cases: Sub-categories that provide special behavior for special cases.

9. Plug-in: The connection class is not compiled at the time of configuration.

10, Service pile: In the test to remove the dependency on the problematic service.

Enterprise-class systems typically rely on access to third-party services such as credit scoring, tax rate queries, and price engines. Developers with this kind of system development experience know that if you rely on external resources that are completely out of your control, you often frustrate software projects. The characteristics of third-party services are unpredictable, and these services are often remote, and thus software performance and reliability can be compromised.

This dependency can cause the test to fail and multiply the development cycle. In testing, replacing the service with a local, fast, in-memory service pile will improve your development experience.

When you find that reliance on a particular service hinders your development and testing, you should use a service pile. Many XP practitioners use the term "mock objects" instead of service piles.
11. Recordset: How tabular data behaves in memory.

The idea of Recordset mode is to provide a complete solution to this problem through an in-memory data structure that looks very similar to the results of a SQL query, but can be generated and manipulated by other parts of the system.

Recordsets are usually not created by you, but are provided by vendors from all software platforms. Ado. The data set in net and row set in JDBC2.0 are examples of recordsets.

Currently there is a memory database SQLite, read access is fast, interested can be researched, is open source.

http://blog.csdn.net/byxdaz/article/details/4811772

"Enterprise Application Architecture mode Chinese Version" study notes (GO)

Related Article

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.