Use the design mode to solidify your C # Program (1)

Source: Internet
Author: User

Use the design mode to solidify your C # Program (1)

Design Patterns: Solidify Your C # Application Architecture with Design Patterns Chinese edition (Part 1)

Author: Samir Bajaj
Translator: glory

[Translation: C # advanced article. The translator simply sorts out the C # examples provided by Samir (some of the Code provided by the author cannot be compiled in the translator's environment) and compiles the corresponding C ++ example, put them in comments for readers to compare. All C # And C ++ debugging environments are Microsoft Visual Studio. NET 7.0 Beta2]

[Summary: by providing a framework, design patterns can solve many problems in application development. The pattern makes the design process clearer and more efficient. It is especially suitable for C # program development because C # is an object-oriented language. Because the origin and starting point of the design model is to describe object-oriented (reusable) software design.] The existing design model provides an excellent template for your own class design, the usage mode can shorten the software development cycle. This article describes several popular design patterns, including singleton, strategy, decorator, composite, and state. You can use them in your own applications to improve application scalability, and makes the class easier to reuse.]

As any sophisticated object-oriented software developer knows, it is incredible to discuss the software design architecture without a minimum understanding of the design patterns. If not all, most software applications, tools, and systems use at least one or more design patterns. The design pattern is a description of a set of interacting classes that provide a framework for solving general problems in a specific context. In other words, the pattern provides a solution for specific problems in object-oriented software development. In addition, patterns generally focus on constraints and other factors that limit their adaptation to solutions. The connection and communication between classes and context details define a mode, it provides a solution for any problem that matches the characteristics and necessary conditions in the object-oriented software design.

I must admit that I am an enthusiastic supporter of design patterns. Since I have read the Creative Book Design Patterns co-authored by Gamma, Helm, Johnson, and Vlissides, I have rarely designed software without any patterns. In fact, I spent a considerable amount of time in the early stages of software design to determine a pattern that would naturally fit the future architecture. After all, the model is a solution to some problems that have been tested by time and application fields. Those problems have been solved by experienced designers, developers, and language experts. It is wise for anyone who is performing software design to make good use of the knowledge and expert experience that can be used. It is often a good idea to use a solution that has been proven to be successful over and over again, rather than creating a new one from the hair.

Almost no developer can enjoy the luxury of writing only small programs. Modern application software and systems are complex. They often consist of thousands of lines of code, and the code above these basic codes is even larger. A simple grasp of tools and languages is insufficient for program design requirements. The company's software development generally requires great flexibility in design and architecture, to adapt to the changing needs of customers at different stages of product development, even after product release. This dynamic nature requires strong software design. It should be able to adapt to changes without causing any unnecessary chain reaction-it should not require rewriting of potential, irrelevant (sub-) systems. Adding features and components to modules that do not have scalability is frustrating and difficult to achieve the expected goal. A closed, non-elastic design will sooner or later be overwhelmed by the changing pressure. The design pattern helps to lay the foundation of the elastic architecture, which is a common feature of every outstanding object-oriented design.

Design patterns have been catalogued to solve small and large-scale architecture-level problems. This article will introduce several popular design patterns that I found useful in my own projects. Although familiarity with the concept of object-oriented design helps to understand this article, I do not assume that you have any preliminary knowledge of design patterns. Although any programming language suitable for object-oriented development can be used to clarify the mode, I will only use C # To compile the example: but I am not J. I have provided a complete example of C ++ corresponding to C #, so that readers familiar with C ++ can compare J ], it also demonstrates the power of this language. I will not discuss any details about the Microsoft. NET class library. On the contrary, I will focus on using the C # language as a tool for Designing object-oriented software.

C # And Design Mode

C # is a modern programming language that provides support for directly ing the syntax structure and semantics of object-oriented design concepts to promote object-oriented software development. This is not the same as C ++. C ++ also supports process-oriented, object-oriented, and generic programming. Even so, if you are a C ++ programmer, it is very easy to follow up with C. For C ++ programmers, this learning curve is quite flat. Even if you have never read any C # code before, there should be no problem in understanding the sample code in this article. In fact, if you find that C # is more clear about the implementation of the design pattern, I will not be surprised, especially if you have previously written code using the design pattern. Generally, books and articles discussing design patterns describe in detail the problems and context details to be solved by the patterns, and then provide a standard solution description. This article is not so rigorous. I only focus on the nature of the model, and I will explain it with appropriate C # examples.

Let's start with the simplest design model: singleton.

Singleton

Any developer who has written an MFC Application (no matter how small the application is) knows what singleton is. Singleton is a unique instance of the class. When using MFC, The Global instance of the application class derived from CWinApp is singleton. Of course, in the MFC application, although it is stipulated that the second instance of the application class cannot be created, nothing can prevent you from doing so. In fact, whether it is VC6.0 or VC7.0Beta2, their compilers can limit the creation of the second instance to a certain extent. To some extent, this is because, in this case, the compiler does not check for you-tries to create a second instance of the application class in a button event of the form.] In this case, when you need a specific class to show singleton behavior, a better alternative is to let the class be responsible for ensuring that only one instance will be created. Back to MFC, we know that the responsibility for ensuring the uniqueness of the application class instance is left to the developer of the application. They must be careful not to create the second instance of the application class.

Now let's look at the classes shown in table 1. Singleton access is limited to instances that must use static methods. In most cases, singleton should have global visibility, which can be achieved by setting its creation method public. Unlike the singleton simulation with global variables, this mode can prevent redundant instances from being created while providing global visibility. Note that the constructor of this class is set to private, which means there is no way to directly create a class Instance by bypassing the Static Method Instance.

Table 1

Class Singleton
{
Private static Singleton singleton = null;
Public static Singleton Instance ()
{
If (null = singleton)
Singleton = new Singleton ();
Return singleton;
}
Private Singleton ()
{
}
}

The singleton mode has more functions than that. In particular, it can be expanded to create a variable number of instances of the class. Assume that an application needs to schedule a worker thread to execute a specific task. Considering saving system resources, we use singleton to implement this thread class. Soon, tasks that require singleton thread processing become intensive. If we decide to expand this application, we can easily increase the number of worker threads, because all the logic of thread creation and access authorization to them are defined in a class.

Another advantage of the singleton mode is that the creation of singleton can be delayed to the desired time, as shown in table 1. Whether or not the global variables are required, they are created at the beginning, but this global object is not always required. C # does not support global variables, but it is still possible that an object is created on the stack at the beginning of a method and will not be used until a long time later. If so, the singleton model provides an elegant solution for such cases.


As a tool, C # is superior to C ++ in the implementation of singleton mode. Although this advantage is subtle, it is absolutely important. Implementation Based on C ++ needs to consider some difficult issues related to life-cycle management brought about by singleton, while in C #, it is automatically handled at runtime. This advantage is meaningful. In the C # implementation version of singleton mode, you only need to ensure that you have a live reference when you need singleton.

The following is a complete example of singleton mode.

C # example:
Using System;
Class Singleton
{
Private static Singleton singleton = null;
Public static Singleton Instance ()
{
If (null = singleton)
Singleton = new Singleton ();
Return singleton;
}
Private Singleton ()
{
}
}
Class Application
{
Public static void Main ()
{
Singleton s1 = Singleton. Instance ();
File: // SingletonS2 = new Singleton ();File: // ErrorError: the constructor is inaccessible.
Singleton s2 = Singleton. Instance ();
If (s1.Equals (s2) // reference equal
Console. WriteLine ("Instances are identical ");
}
}

/* The output result is as follows:
Instances are identical
*/

C ++ example, it is only for the convenience of reading and comparing]

# Include "stdafx. h ";
# Include
Class Singleton
{
Public:
Static Singleton * Instance ()
{
If (NULL = singleton) singleton = new Singleton ();
Return singleton;
};
Private:
Singleton ()
{
};
Private:
Static Singleton * singleton;
};
Singleton * Singleton: singleton = NULL;
Int _ tmain (int argc, _ TCHAR * argv [])
{
Singleton * sgt1 = Singleton: Instance ();
Singleton * sgt2 = Singleton: Instance ();
If (sgt1 = sgt2)
Cout <"Instances are identical ";
Delete sgt1; // note: In this simple example, there is no memory leakage or tricky life-cycle management problem]
Return 0;
}
/* The output result is as follows:
Instances are identical
*/
]
Strategy

Applications often run different tasks based on user input, platform running, and deployment environment. In disk format

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.