zoukankan      html  css  js  c++  java
  • 设计模式之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这个类

  • 相关阅读:
    转:使用vs2013打开VS2015的工程文件的解决方案(适用于大多数vs低版本打开高版本)
    linq 动态组合条件
    转:Web应用程序项目XX已配置为使用IIS
    转:centos彻底删除文件夹、文件命令
    转:WebClient类(温习一下)
    解决 ORA-12514: TNS: 监听程序当前无法识别连接描述符中请求的服务
    转:装完Centos7提示Initial setup of CentOS Linux 7 (core)
    PL/SQL Developer 登录 Oracle 12c和Win10下安装Oracle 11g
    centos7-linux安装docker(离线方式)
    windows7安装gitblit
  • 原文地址:https://www.cnblogs.com/yi/p/405127.html
Copyright © 2011-2022 走看看