Object-oriented design strategy of the application service layer design ---- talk Websharp middleware: SUN Ya-min
Preface The N-layer application software system, due to its many advantages, has become a typical software system architecture, and has also been known for the majority of developers. In a typical three-layer application system, the application system is usually divided into the following three levels: the database layer, the application service layer, and the user interface layer. As shown in the figure below: where the application service layer sets the processing of the service logic of the system, it can be said that it is the core part of the application software system. Software system's robustness, flexibility, reusability, upgradeability, and maintainability, to a large extent on the design of the application service layer. Therefore, how to build a good architecture application service layer is a problem that application software developers need to focus. In order to achieve the best effects of the application service layer, we usually need further functional analysis and level segmentation of the application service layer. Many developers are constructed when building a service layer, and the business logic handling or even interface is displayed together, or the business logic processing is equivalent to database manipulation, and so on, these are defective practices. In this paper, there are some discussions that can be used in this regard. In order to make the discussion more targeted, this paper discusses some popular system architectures, such as J2EE architectures, and JDO. On Microsoft's .NET platform, it will take the Websharp middleware as an example. The WebSharp middleware is a middleware system built on the Microsoft's Net platform, and is also a support system for the system architecture described in the article. These architectures do exemplified, because .NET has time shorter, currently there is no mature unified architecture on this platform, and J2EE is the most mature platform for constructing enterprise applications. Since I have published many feedback and letters, I have received many feedback and letters since I have published many feedback and letter. Because of the time relationship, you cannot reply one by one, so I also borrow some answers to everyone. It should be noted that the original JobsInfo has now been upgraded, the name is changed to Websharp. The principles of design and evaluation standards are the same as software engineering, and the design of the application service layer must follow the most important principles of high polymerization and low coupling. The original purpose of software layers is to improve software maintainability and reusability, while high polymerization and low coupling are the principles necessary to follow this goal. Try to reduce the coupling between the individual parts of the system, it is a problem that needs to be considered in the application of service layer design. Neglocal and coupling, including the relationship between the horizontal and longitudinal direction. Features and data coupling are the goals we need to reach. The horizontal cohesive and coupling, typically reflecting the relationship between the various modules, classes of the system, and longitudinal coupling, reflecting the relationship between the various hierarchies of the system. The system's framework usually includes a range of specifications, conventions and support libraries, and services. For how to determine the system framework of a software, the author believes that you can judge from the following aspects: ◆ The internal and coupling of the system is to ensure that the architecture of a system is in line with the primary standard of software engineering principles. ◆ Level Clear and Simpleness System Each part of the completion function and goals must be clear, the same function, should only be implemented in one place. If a feature can be implemented in the system, then it will bring problems with later development and maintenance. The system should be simple, too complex system architecture, will bring unnecessary cost and maintenance difficulties. In the case of as much as possible, a portion should complete a separate and complete function.
◆ Easy to achieve sex if the system architecture is very difficult, even exceeds the existing technical capabilities of the team, then the team has to spend a lot of energy for the development of architecture, which may have to be lost for the entire project. Simple is beautiful. ◆ Upgrade and expandability a system framework, limited to technical conditions, or the limitations of the designer's understanding of the system, may not take into account all the changes in future changes. However, the system must be prepared for future possible changes, it can be evolved on the future, but will not affect the original application. Interface technology is a common application in this regard. ◆ Whether it is conducive to teamwork to develop a good system architecture, not only from the perspective of technology, but it should also be applicable to team development models, which can facilitate the mutual collaboration of different roles in the development team. For example, separate the web page and business logic components, but make the page designer and programmers to work synchronize without each other. ◆ Performance is important for software systems, but sometimes, in order to make the system get more flexibility, it may have to be balanced in performance and other aspects. In another aspect, due to the rapid development of hardware technology, performance problems can often be improved by using better hardware. The content application service layer of the application of the service layer is often also referred to as the business logic layer, because this layer is part of the application software system business logic processing set. However, I refer to this layer as the application service layer, not known as the business logic layer, because this layer needs to be dealt with just business logic, but also contains other content. From a complete point of view, the application service layer needs to process the following: ◆ Data representation data is the object of software processing. From a certain extent, "software, the data structure plus algorithm" is a certain meaning. In an object-oriented system, the data is represented by class, representing the abstraction of the real world entity object in the software system. Consider the so-called MVC mode, this part of the class belongs to the category of the M-entity class. Since applications typically use the database, data in the database, it can be regarded as the persistence saving of the object. Since the database is generally a relational, this section, it is also necessary to consider mapping of class (object) with relational data, which is usually said O-R Map problem. ◆ Access method of data is as described above, the physical object data processed by the software system requires persistence to save the database, so we must handle the system's interaction with the database, and the problem of data access and conversion. ◆ The organization of business logic is in an object-oriented system, and the business logic appears to interact between objects. With the above entity object, as well as the saving strategy of the object, you can combine these objects to write our business logic handler. In the processing of business logic, the correctness and integrity of the processing must be guaranteed, which will involve transaction processing. Typically, we will also encapsulate business logic into components to obtain maximum reusability. ◆ How to provide services for business services After we complete the system's function, how to serve customers is the problem we need to consider. The customer here refers not to the software of the software, but also including the calling interface, other programs, etc. For example, in a web-based ASP.NET or JSP system, customers of business logic functions are these ASP.NET pages or JSP pages.
What ways, direct, or indirect, providing services to these customers, is the task that needs to be completed. ◆ Deployment of the layer and interlayer interaction For a multi-layer application software system, especially large application software systems, different parts are often required to deploy different parts on different logic or physical devices. Especially some web-based applications, its deployment will involve different service devices such as web servers, component servers, database servers. In the design of the application software architecture, there must be considered a variety of different deployment scenarios. In summary, a complete web-based application software system, its architecture can be represented by the following figure (Websharp recommended application software system architecture): For all aspects, each problem can have many strategies and Solution, however, in a system, it should be as unified as possible. That is to say, in one system, or one project, each of the methods that solves each problem should be uniform. The development method of software is flexible, can solve the same problem with different methods, which will induce developers to adopt the methods they believe to express their own methods, but from the entire system, this will be disastrous. We should be as uniform as possible, that is, use a unified data representation, unified data access mode, unified business logic processing method, etc. Below, some detailed discussion will be conducted on the design strategies and available schemes of these parts. Data entities represent application software systems, from essentially the simulation of computers on real world. In the real world, the entity objects in the software system are manifesting as data that needs to be processed. In an object-oriented system, this is expressed by "class" and "objects". Refer to the famous "MVC" mode, the class can be divided into the entity class (M), the Control class (C), and the boundary class (V), which represent the entity object, control, and interface display, respectively. Data that requires processing in the system, in an object-oriented system, belongs to the entity class. When considering the design strategy of the data entity layer, you need to grasp the following points: ◆ Consistent data representation. In one system, the data representation must be as uniform as possible, while processing a single data and multiple data, the processing method is as consistent. ◆ Because data is usually needed to be stored in the database, good mapping methods are required. ◆ Handle the particle size of the object, that is, the so-called coarse granular object, fine particle object. General examples Consider a real-one example, a product in a warehouse, in the system, can be used in the system: public class product {public string name; // Name
Public Decimal Price; // Price
Public int count; // quantity
}
You can use the Product class as follows:
Product p = new product ();
// ...... Processing Product
This is a definition of a Product class that contains three properties. For convenience of explanation, here we try to simplify the problem.
Another example, a ware list can be defined as follows:
Public class form {public string id; // Introduction list number
Public datetime addtime; // Introduction time
Public formdetail [] formdetails; // Introduction
}
Public class formdetail {
Public product Inproduct; // Introduction Product
Public int count; // Number of warehouses
}
For processing a single object, the above method is usually used, but when we need to handle a set of objects, it is to handle a collection of objects, there will be some small trouble.
As mentioned earlier, we hope that the way to deal with a single object and object collection, which is tried to unify, which is very large for software development. Commonly used methods of processing objects:
◆ Method of array representation
For example, the above example is a method employed when a library contains a plurality of warehousing units. For flexibility, the container can also be used, such as Vector or C # ArrayList (C #) in Java. Just, a type conversion is required when processing the object. This issue does not exist in the generic language, such as the container class of the standard library of C .
◆ ObjectCollection method. This method is similar to the above method, and the difference is that a Collection class is designed for each entity class. For example, you can design a FormDetailScollection class for FormDetail (C #):
Public Class FormDetailsCollection: arraylist
{
Public Void Add (FormDetail Detail)
{
Base.add (detail);
}
Public New Formdetail this [int Nindex]
{
Get {return (formdetail) Base [NINDEX];
}
}
}
The benefit of this is that when the object in the operation collection does not have to perform the type of conversion operation.
◆ The representation method of the data set.
With this method, it is usually directly used as a data set from the database query as a data processing object. This approach is a very common approach in the ASP application. This practice is simple, and beginners are easy to master, but there are many ills.
EJB method
In the J2EE system, the typical method for the processing of the entity object is Entity Bean. The Entity bean is used in J2EE to represent data, as well as persistence storage of package data (interact with the database). Since the Entity Bean is consumed by the resource, and the remote call is used to access, there will be some "value objects" in the need to pass a large amount of data or pass data between different hierarranges. (Value " Object) design mode to improve performance. About more content of the design pattern in J2EE, readers can refer to the "J2EE core mode" book.
JDO method
JDO provides a relatively "lightweight" program relative to J2EE this expensive approach. In JDO, you can use a general approach, write a physical class, and then strengthen these classes through some enhancers to make it conform to the JDO specification, and finally, you can implement the persistence of the object via the PersistenceManager.
Whether it is EJB or JDO, an XML configuration file is used when mapping it with a database. This is a flexible way. Due to the powerful expression of XML, we can use it to describe the mapping relationship between the entity class and the database in the code, and do not have a hard coding in the code, so that when the situation changes, it is possible Just modify the configuration file without having to modify the source code of the program. More information about the configuration files of EJB and JDO, you can refer to the relevant documentation, here is not described here. However, the way using the XML configuration file is not the only way, in some cases provided by Microsoft, such as the duwamish example, no use. As for which method is specifically used in the development process, it is necessary to trade off and hit according to the specific situation.
WEBSHARP method
WEBSHARP has taken advantage of the functionality of DataSet in the .NET Framework class library, and designs an ENTITYDATA class. This class inherits DataSet and adds some properties and methods. Similarly, the mapping relationship with the database is also a way of using an XML configuration file.
In actual applications, you have to get an entity object, which can be obtained in the following:
EntityData Customer = EntityDataManager. GetemptyEntity ("Customer");
Then, the properties of this object can be accessed by the following manner:
String Customerid = Customer ["Customerid"]
It can be seen that this approach is a bit different from the traditional way. In this way, the performance of the data is only one, that is, EntityData. The advantage is obvious. It is not necessary to write a class separately to each entity, which can greatly reduce the number of code. Its shortcomings are also very obvious, that is, it is not possible to use the compiler type detection. If you call the object's properties, the name of the wrong property may be wrong, however, this problem can be solved by tools.
About this area more detailed information, please refer to 文:
"
Use the .NET framework development application system "
"
Enthusiastic secret: development .NET platform application system framework "
Data access method
The purpose of data access is to persistence saving objects, so as to use, such as query, modification, statistical analysis, etc. Access objects can be a database, normal file, XML or even any other way, as long as the data can be saved for a long time, and will not be affected by factors such as power failure, system restart. In this section, the ideal situation is naturally able to support various types of access to various types other than the database, or at least an interface can be more convenient.
Because the database is the most common, it is also the most effective data storage method, so supporting the data settlement is the first first to support. Under different platforms, there are different ways to access different databases. For example, under the Java platform, there is JDBC, under the Windows platform, you can use ADO, ADO.NET, etc. However, these means are more close to the bottom layer. When actually manipulating the database, we need to write a lot of code, and we also need to perform the work of object-oriented data in the program to the relational database by manual way. Doing this, the efficiency of natural programming is not high, and it is very easy to make mistakes. However, it is undeniable that this is also a way that can be selected.
From another aspect, since we have solved the data mapping problem in front, it is very regularly in terms of data access, we can perform this job through the framework. In this way, we can simplify a lot of workload works with the code of interaction with the database, which can reduce the chance of bugs, on the other hand, because the frame packages the differences between different databases, make us do not need to consider when writing procedures Differences between different databases, and give this job to the framework to achieve the software's background database independence. At this part, the following two parts of the following are particularly important:
◆ Object-relational map analysis class, can complete the object-relational mapping by established scheme, determine data access scheme
◆ Database manipulation: Depending on the mapping relationship, the data is accurately stored in the database and the differences between different databases are encapsulated.
This part of the operation process, can be expressed as shown below:
In J2EE, this part is typical is CMP in EntityBean. Since the interaction part of the database needs to be implemented by manually writing code, it is difficult to enjoy the convenience of the container, but due to the standards of EJB2.0, CMP function, including mapping capabilities, entity The function of the relationship model is relatively weak, so in many times, we have to use BMP. Now, EJB2.0 is very powerful in this area, we can enjoy the convenience of containers, and put most energy in achieving more complex business logic.
In JDO, you can also achieve the same goals through the PersistenceManager, for example, you want to save a Customer object to the database, you can use the code similar to the following:
Customer Customer = New Customer (...);
PersistenceManager PM = pmfactory.initialize (...);
Pm.Persist (Customer);
The code is equally simple and intuitive, and there is no big pile of database-operated code, and it is not easy to have errors.
Websharp program
Webshap defines the IentityDao interface for the category of the data, which is defined as follows:
Public Interface Intitydao
{
Void insertity (entityData entity);
Void UpdateEntity (EntityData Entity);
Void deletentity;
EntityData FindByPrimaryKey (Object KeyValue);
}
For each entity class, you can implement the data accessed by expanding this interface. However, since this interface does not provide any implementation method, when it is implemented for each implementation, if it is directly expanded from this interface, the code implemented must also be manually fill it. In order to improve the development efficiency, reduce code writing quantity and bug possibilities, the framework provides the AbstractSingletableDao and AbstractMultitableDao.cs classes, which extends from INTYTYDAO, which implements database access methods for single database tables and multiple database tables, to achieve database access methods for single database tables and multiple database tables, respectively. And, implement the IDisposable interface. In this way, when we actually write code, we only need to inherit these two classes.
For example, the Customer class's data access class can be defined as follows:
Public Class CustomERENTITYDAO: AbstractSingletabledao
Then you can use it in your code:
Customer Customer = ...
USING (CustomERENTITYDAO CDO = New CustomERENTITYDAO ())
{
CDo.uPdateEntity (Customer);
}
More general, Wensharp also provides the PersistenceManager class that can be used to store data in EntityData into the database. This class contains two methods: Persistentity and Deletentity. If you don't want to write a dedicated DAO class for a physical class, you can also use this class to manipulate the entity object. However, currently, only automatic storage of objects mapped to a single table is supported. Below is an example:
PersistenceManager PM = persistenceManager.initial ();
PM. Persistentity (Entity);
In order to encapsulate a different database, a unified database access interface is necessary. For the contents of writing a general database access, you can see you: "
Use the design mode to build a universal database access class. "
In this section, it should be noted that in order to ensure the integrity of data storage, the function of transaction should be considered. J2EE, JDO and Websharp support use transaction when data storage.
Business logic processing
With the work above, we can combine these objects to write our business logic. In an object-oriented system, the business logic appears to be interactive between objects. In some simple systems, there is no complex business logic, just some data maintenance work, then there are two parts of the above, we actually have already forgotten most of the work.
At this part, because the business logic between different systems is very different, there is basically no way to provide a unified mode. However, it should be noted that in the same system, the basic consistent strategy is very necessary, which helps to eliminate inconsistencies inside the project to make the project more controllable. Even these strategies can expand into a company part, or even the strategy of all projects.
It is worth noting that many people operate the database in this part, and the business logic processing is equivalent to database operation, which is not advisable. In business logic processing, the processing should be an object, not directly to deal with the database, so that a better system structure can be obtained.
It is necessary to provide some support from the business logic processing section. This is the most important thing is the process of transaction. The processing of business logic involves interaction between multiple objects, as well as interactions with the database. In order to ensure the integrity of the process, transaction methods must be used. The frame must support transaction processing.
The function of transaction processing basically has two options: using a database-based transaction, using external business processing services.
With database-based transactions, transaction processing is relatively high, but when the system involves interaction between multiple databases, the database connection is unable to force. The use of dedicated transaction processing services can adapt to more situations, and have tests show that as data processing is increased, the performance difference between the two will gradually decrease.
In J2EE, the container provides the ability of transaction processing. On the .NET platform, transaction is available through Windows Com service. In WebSharp, a simple package is made for Com service. At the same time, a database-based transaction can also be used. The following is a simple example, which means a process of incorporating a library list. In this process, you need to modify the existing stock of each product on the library:
Public void storeintowarehouse (EntityData INSERTFORM)
{
INSERTFORM.SETCURRENTTABLE ("FormDetail");
TransactionManager Transmanager = New TransactionManager ();
ProductDAO PRODAO = New ProductIns (TRUE);
FormentityDao Formdao = New FormentityDao (TRUE);
Try
{
IF (Insertform.currentTable.Rows.count> 0)
DO
{
String productId = insertform ["productID"]. TOSTRING ();
Decimal Incount = INSERTFORM.GETDECIMAL ("Incount");
EntityData Product = ProductDao.FindByPrimaryKey (ProductID);
Product ["currentcount"] = product.getDecimal ("currentcount") incount;
Transmanager.addmethod
New TransactionManageDFunction (ProductDao.UpdateEnt ", Product);
} while (insertform.next ());
Transmanager.addmethod
New TransactionManageDFunction (FormDao.insertentity), Insertform);
Transmanager.executeMethods ();
}
Catch (Exception EE)
{
Throw EE;
}
Finally
{
ProductDao.Dispose ();
INSERTFORM.DISPOSE ();
}
}
Business service
The purpose of business facade is to isolate the provider and user of the system function, more specifically, the user interface that isolates the software logic (see FACADE design mode). This layer does not have any logic that needs to be processed, just as a buffer of the background logic processing and the front-end user interface to achieve the following purposes.
◆ Separate user interface and system business logic processing so that when business logic changes, it is a design method that supports changes.
◆ Make the same business logic to handle different client requests. For example, Facade can be designed as a Web Service so that it is possible to provide services for traditional WinForm client programs, web programs, and other external systems, while using the same application service layer, while also achieving distributed deployment of the system. For this, you can see the Demo program attached herein.
◆ As a call interface between the different modules of the system. A system typically contains many modules that are relatively independent, and they may be called each other. In order to reduce the coupling between the different parts, a certain design method must be used, and the FACADE design mode is a very effective, and it is also the foundation of the business appearance layer. ◆ It is conducive to the division of labor of the project team. As an access interface, the business appearance layer separates interface designers and logical designers, making the development of the system to achieve longitudinal division of labor, different developers can pay attention to their own field without being interfered.
The code framework of the business appearance layer, can be completed after system analysis and design, the method he needs to provide, which is equivalent to signing an agreement between interface designers and logical designers, although he does not implement any logic, but His introduction can make the system's development more organized and more concise. The set of words on "Design Mode" is, "any problem, can be simplified by introducing an intermediate layer."
Tailor
The above four levels are very necessary for large application software systems. However, for some small application software systems, if fully followed by the above level, it may affect the work efficiency. Therefore, for different systems, the architecture can be taken to cut.
Data entity layer and entity control layer are required for each application software system, obviously unable to cut. For business logic layers and business appearance layers, according to entity, the following cuts can be performed:
◆ If the system does not have a complex business logic, but only some data is operated, or the business logic is particularly small, then the business logic layer can be omitted, and the related function is moved to the entity control layer.
◆ If you do not consider the situation of multiple clients, the problem of distributed deployment is not considered, the system's module is very small, and there is no case in which the module is tight, then the business appearance layer can be used, and the user interface program can be used Direct access to business features.
In the above discussion, for each level, there are various programs that can be selected. Each solution has his advantages and disadvantages. During the specific development process, it is necessary to take place according to the specific situation.
In addition to the system
Application software system architecture is an important part of software engineering. Design a good frame, its purpose is clear, that is, before the "silver bomb", do not have the largest possible, improve the efficiency and software quality of software development, and make unnecessary work and easy error work, Treatment to the frame.
Applying the service layer, in the software system, it is a very complicated part. At first glance, there is no rules, giving people the feeling of starting. Our goal is that they are not regular as regular, and the regular things are extracted, forming specifications, thereby reducing future development efforts. The method is to reasonable layering for the system, so that the system's level is clear, each level is completed, which means that each level is relatively more regular, so we can Give these regular things to the frame to perform, or develop a auxiliary tool to complete this part of the code write work. Websharp provides tools for such code automatically generated. This tool is designed as a plugin for the Visual Studio.NET integration development environment, which can provide a lot of convenience during actual development. This is another benefit that the system level is clear.
For a software company, the meaning of the unified system framework is not only the software development itself. A unified system framework is also an important part of the company's knowledge management. If there is a clear software framework for one or limited number, these frameworks can become a carrier that condense the company's experience, wisdom, and can be enrichment and perfect in constant practice. Since the company's software system's framework is relatively unified, then when a project is replaced or increasing developers, the later people can easily take over, which is very important for the company's development management. About the system framework is related to the relationship between knowledge management, because it is not the focus of this article, it is limited to the relationship of the space, so no more details will be described.
Conclusion
The application service layer of the application software system is very complicated. In order to make the system's structure is more clear, we need to divide the system to further level division. For each level, there can be a variety of design strategies, and each policy is not perfect, which requires us to take care of it in practice.
Limited to my awareness and level, what is the views and methods in the article or inappropriate, please advise, discuss it.
Attachment:
A DEMO program developed using WebSharp middleware.
About the author: Sun Yamin, graduated from Nanjing University in 1998. At present, a master's degree in China University of Science and Technology, and a technical directors of a software company in Suzhou can contact him through sunny_y_m@163.com.