Curing pattern design program in C #

 

 

Yi Xu:  C # Advanced articles. Samir translator for C # example provided by a simple order (some code provided by the author in the translator's environment can not compile), and the preparation of the corresponding C ++ example, put together in Annotation, so that the reader comparison. Translation of all C #, C ++ debugging environment are Microsoft Visual Studio.NET 7.0 Beta2.

Summary:  By providing a framework, design patterns can solve many problems in application development. Mode makes the design process more clear and efficient, it is especially suitable for C # developers, because C # is an object-oriented language. 【Annotation: Because of design patterns origin and the starting point is to describe the object-oriented (reusable) software design】 existing design patterns provides an excellent template for your own design class, usage patterns may shorten the software development cycle. This article will describe several popular design patterns, including singleton, strategy, decorator, composite and state, you can use them in your own applications, thereby improving the scalability of the application and make it easier to reuse the class.

   As any seasoned object-oriented software developers are aware, the lack of the most basic understanding of design patterns from discussions of software design architecture is incredible. If there are not all that most software applications, tools and systems use at least an even more design patterns. Design pattern is a description of a class of interaction, these classes provide a framework for solving the general problem of specific contexts. In other words, the pattern provides a solution to the problem object-specific software development. In addition, the pattern generally limit its attention to adaptation solutions related constraints and other factors. And a communication connection between the details and the context classes and together define a pattern, the problem that any object oriented software design and characteristics of the matching conditions necessary to provide a solution.

   I must admit I was an ardent supporter of design patterns. Ever since I read the Gamma, Helm, Johnson and co-author of that Vlissides inventive book "Design Patterns" since I rarely do any pattern and design software. In fact, I spent considerable time in the early stages of software design can be used to decide the future architecture and natural fit model. After all, the model is tested the elapsed time and applications for some solution to the problem, that problem has been solved and experienced designers, developers, and language experts. Any person going to a software design perspective, use could be using the knowledge and expertise is wise. The use has been repeatedly proven to be a successful solution and not a new invention from scratch is often a good idea.

   Few developers can write only enjoy the luxury of a small program. Modern applications and systems are complex, they are often composed of thousands of lines of code, and the code on the basis of these codes are even more enormous. Just simple tools and mastery of language is not adequate for the requirements of programming, software development companies are generally required to have great flexibility in design and architecture to adapt to changing demands in different stages of the customer's product development, even after the product launch is often the case. This dynamic requirements of software design must be robust. It should be able to adapt to change and will not cause any unwanted chain reaction - should not require rewriting potentially irrelevant (sub) systems. Add features and components to the module does not have expansion capability is frustrating and difficult to achieve the desired objectives. Closed, inelastic design change sooner or later be crushed by the pressure. Design patterns help lay the foundation flexible framework, which is a common feature of every good object-oriented design.

   Design patterns have been cataloged classified to solve small problems even for large-scale architecture-level issues. This article will introduce several popular design patterns in my own projects, I find them very useful. Although familiar with the object-oriented design concept helps to understand this article, but I do not assume you have any prior knowledge of design patterns. Although any suitable object-oriented development programming language can be used to elucidate the mode, but I will only be written example using C # [Annotation: But I'm not J I am giving you a complete sample and C # corresponding C ++ in order to be familiar with C ++ readers to compare J], but also to take this to demonstrate the power of the language. I will not discuss any details of the Microsoft .NET class libraries. Instead, I will focus on the use of C # language as a tool to design object-oriented software.
C # and Design Patterns

   C # is a modern programming language, which directly maps the syntactic structure and semantics support object-oriented design concept by providing to promote object-oriented software development. This is very different from C ++, C ++ supports process-oriented, object-oriented and generic programming. Nonetheless, if you're a C ++ programmer, follow up C # is very easy. For C ++ programmers, the learning curve is fairly flat. Even if you have never seen before in any C # code, understand the sample code in this article should not have any problems. In fact, if you find that C # design patterns to achieve greater clarity, I will not have any surprise, especially if you have previously used design patterns to write code to words. General discussion of design patterns books and articles will be described in detail mode to solve the problem and context details, and then provide a description of a standard solution. This article will not be so strict, my only concern is the nature of models, supplemented by the appropriate C # examples to be described.

   Let's start with the simplest design pattern began: singleton.

singleton 

   Any MFC developers who write applications (application no matter how little is written) knows what is singleton. singleton instance of the class only. When using MFC, it is a singleton instance of the application from the global CWinApp-derived class. Of course, in MFC applications, although the provisions are not allowed to create a second instance of the application class, but there is nothing to stop you to do so. 【Annotation: In fact, whether or VC6.0 VC7.0Beta2, their compilers can limit you create a second instance of a certain extent. The reason why a certain extent, because the compiler such as this case does not help you check - try to create a second instance of the application class in the form of a button in the event] In this case, when you need a when a particular class showed a singleton behavior, a better alternative is to make sure that this class will only be responsible for their own created one and only one instance. Back to MFC, we know that the only instance of the class to ensure the application of liability is left to the programmer to develop applications, he (she) must be careful not to create a second instance of the application class.

   Now take a look at the class shown in Table 1. Access is limited to singleton must Instance by static method. In most cases, singleton should have global visibility, which can be achieved by the creation of its methods public. And various analog global variable singleton, this model can prevent the creation of an excess of example, while both the global visibility. Note that the class constructor is set to private, which means that there is no way to bypass the static method Instance to create an instance of the class directly.

   Table 1

class Singleton
{
private static Singleton singleton = null;
public static Singleton Instance()
{
if (null == singleton)
singleton = new Singleton();
return singleton;
}
private Singleton()
{
}
}


   singleton pattern effect more than that, in particular, it can be extended to create a variable number of instances of the class. Assuming an application, when you need to perform specific tasks you need to schedule a worker thread. Considering the save system resources we use to achieve this thread singleton class. Soon, the need singleton thread processing tasks become dense up, if we decided to expand this application, we can easily increase the number of worker threads, because all logical thread creation and their access authorization are defined in a class.

   Another advantage is the singleton singleton pattern created can be delayed until when really needed, as shown in Table 1. No matter whether you need global variables start to be created, but the global object is not necessarily always needed. C # does not support global variables, but it is still possible at the outset of a method to create an object on the heap and use it until much later. If so, singleton pattern provides an elegant solution for such cases.

   In addition, as a tool in the realization of singleton mode, C # than C ++, although this advantage is very subtle, but definitely important. Need to consider a number of thorny issues and life cycle management to bring about the realization of singleton C ++ based, and automatic processing of runtime in C # by. This advantage is significant in the singleton pattern in C # version, you only need to ensure that when you need a singleton, you can have a live reference.

   Annotation: The following is a complete example of the singleton pattern

   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();
//Singleton s2 = new Singleton(); //错误:构造器不可访问
Singleton s2 = Singleton.Instance();
if (s1.Equals(s2)) // 引用相等
Console.WriteLine("Instances are identical");
}
}

/*以下是程序输出结果:
Instances are identical
*/


   C++示例:【译注:译者在自己的程序实践中,几乎从未将类的声明和实现搅和在一起,此处示例代码之所以是如此写法,只是为了便于大家阅读和比对而已】

#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\n";
delete sgt1;//【译注:这个简单的例子里,是不存在内存泄漏或棘手的生命期管理问题的J】
return 0;
}
/*以下是程序输出结果:
Instances are identical
*/


strategy 

   应用常因用户输入、运行平台和部署环境等的不同执行的任务亦不相同。以磁盘文件异步I/O举例,Windows NT/2000下的Win32 API对异步I/O提供了原生支持,但Windows 95/98并非如此。因此,依赖于异步文件I/O的应用就必须实现两套不同的算法,根据部署环境不同,一套可使用Win32 API,另一套可能要采用多线程技术从头写起。而对于客户来说一般不会意识到执行了不同算法,他(她)们所关心的只是得到同样的结果,他(她)们也只关心这个。

   另一个例子是从互联网上的远程服务器下载文件。提供文件下载服务的应用接受一个URL和一个协议(如FTP或HTTP),然后创建一个使用该协议和远程服务器通讯的对象。根据用户不同输入,使用不同的算法(协议)。但结果是一样的:下载了一个文件。

   让我们看一个更具体的例子:素数测试。表2所示的代码声明了一个接口(C#中的一个概念),它只有一个方法:IsPrime。

   表2

interface Strategy
{
bool IsPrime(int n);
}


   接口就象一个合约,它是所有派生类必须遵从的规范。更为特别的是,它定义方法的签名但并不实现它们,实现接口的具体类必须提供这些方法的实现。在这一点上,C#明显优于C++,因为C++缺乏对接口在语言上的原生的支持。C++程序员一般是通过定义只包含纯虚成员函数的的抽象类来创建接口。在C#中,所有接口成员都是public的,所有实现接口的类都必须实现接口中所有方法。

   现在假定我们有三个不同的素数测试算法,每一种都有自己的性能和精度指标。其中之一属于计算密集型,对因数进行彻底测试,另外一种算法速度较快但对大数的测试结果未必准确。我的应用就是要询问用户期望何种执行性能,然后根据其选择调用相应的算法。我把算法封装到实现Strategy接口的若干个类中。参见表3示例代码。

   表3

class Fermat : Strategy
{
public bool IsPrime(int n)
{
bool result = false;
//使用Fermat法测试n是否为素数,果真,则更新result的值
Console.WriteLine("Using Fermat's test");
return result;
}
}

Guess you like

Origin www.cnblogs.com/bbc2020/p/12457273.html