设计模式之Singleton和Factory

 由于是本人第一次写blog而英文又较差,所以翻译不好,请见谅
大家可能看过,因为中文书已经出来了.找不到电子版,所以先用英文(Dissecting A CSharp Application)
因为觉得书写得不错,所以拿出来,与大家分享


Singleton:

singleton模式是对象创建目标型的模式。它确保了仅有一种对象在运行时被实例。同时,提供给我们在全局范围内访问它。


应用程序在运行时,需要一个对象的实例时,使用singleton模式


例子:

class ExampleSingleton {

public void PrintHello() {

System.Console.WriteLine( "Hello World" );

}


ExampleSingleton() {}


static ExampleSingleton exampleSingleton = new ExampleSingleton();


public static ExampleSingleton Singleton {

get {

return examleSingleton

}

}

}


singleton对象有一个私有的构造。这个确保对象不能从我们的singleton类外面创建;因此我们在任何时候仅有这个对象


Factory

Factory模式创建一个对象在一系列可能的class外。例如:当我们需要接口并且我们超过一种方式实现,可以用factory创建一个实现该接口的对象,factory能提供给我们一个实例。


创建一个end product是抽象,这点非常有用(例如,在一些构造不能足够好)

例子:


public interface IhelloPrinter {

void PrintHello();

}


public class EnglishHelloPrinter : IHelloPrinter {

public void PrintHello() {

System.Console.WriteLine( "Hello World" );

}

}


public class GermanHelloPrinter : IhelloPrinter {

public void PrintHello() {

System.Console.WriteLine( "Hallo Welt" );

}

}


public class HelloFactory {

public IhelloPrinter CreateHelloPrinter( string language ) {

switch( language ) {

case "de":

return new GermanHelloPrinter();

case "en":

return new EnglishHelloPrinter();

}

return null;

}

}


在这个例子中,需要一个HelloFactory对象而这个factory创建了IHelloPrinter。这点在设计中更富有扩展性


在这个模式下,我们能很容易往HelloFactory添加我们所需要的HelloPrinter.使用HelloPrinter类仅仅只需要知道factory这个类

原文地址:https://www.cnblogs.com/yi/p/405127.html