中国IT动力,最新最全的IT技术教程
最新100篇 | 推荐100篇 | 专题100篇 | 排行榜 | 搜索 | 在线API文档
首 页 | 程序开发 | 操作系统 | 软件应用 | 图形图象 | 网络应用 | 精文荟萃 | 教育认证 | 硬件维护 | 未整理篇 | 站长教程
ASP JS PHP工程 ASP.NET 网站建设 UML J2EESUN .NET VC VB VFP 网络维护 数据库 DB2 SQL2000 Oracle Mysql
服务器 Win2000 Office C DreamWeaver FireWorks Flash PhotoShop 上网宝典 CorelDraw 协议大全 网络安全 微软认证
硬件维护  CPU  主板  硬盘  内存  显卡  显示器  键盘鼠标  声卡音箱  打印机  机箱电源  BIOS  网卡  C#  Java  Delphi  vs.net2005
  当前位置:> 程序开发 > 编程语言 > Java > 设计模式
[Creational Patterns] The Singleton
作者:未知 时间:2005-07-24 21:23 出处:JR 责编:chinaitpower
              摘要:[Creational Patterns] The Singleton
The 23 design patterns selected for inclusion in the original Design Patterns book were ones which had several known applications and which were on a middle level of generality, where they could easily cross application areas and encompass several objects. The authors divided these patterns into three types creational, structural and behavioral.
?Creational patterns are ones that create objects for you, rather than having you instantiate objects directly. This gives your program more flexibility in deciding which objects need to be created for a given case.
?Structural patterns help you compose groups of objects into larger structures, such as complex user interfaces or accounting data.
?Behavioral patterns help you define the communication between objects in your system and how the flow is controlled in a complex program.
Creational Patterns
All of the creational patterns deal with the best way to create instances of objects. This is important because your program should not depend on how objects are created and arranged. In Java, of course, the simplest way to create an instance of an object is by using the new operator.
Fred = new Fred(); //instance of Fred class
However, this really amounts to hard coding, depending on how you create the object within your program. In many cases, the exact nature of the object that is created could vary with the needs of the program and abstracting the creation process into a special ?reator?class can make your
program more flexible and general.
The Factory Method provides a simple decision making class that returns one of several possible subclasses of an abstract base class depending on the data that are provided.
The Abstract Factory Method provides an interface to create and return one of several families of related objects.
The Builder Pattern separates the construction of a complex object from its representation, so that several different representations can be created depending on the needs of the program.
The Prototype Pattern starts with an initialized and instantiated class and copies or clones it to make new instances rather than creating new instances.
The Singleton Pattern is a class of which there can be no more than one instance. It provides a single global point of access to that instance.
Structural Patterns
The Adapter pattern can be used to make one class interface match another to make programming easier. We?l also look at a number of other structural patterns where we combine objects to provide new functionality. The Composite, for instance, is exactly that: a composition of objects, each of which may be either simple or itself a composite object.
The Proxy pattern is frequently a simple object that takes the place of a more complex object that may be invoked later, for example when the program runs in a network environment.
The Flyweight pattern is a pattern for sharing objects, where each instance does not contain its own state, but stores it externally. This allows efficient sharing of objects to save space, when there are many instances, but only a few different types.
The Fa?de pattern is used to make a single class represent an entire subsystem
The Bridge pattern separates an object? interface from its implementation, so you can vary them separately.
The Decorator pattern can be used to add responsibilities to objects dynamically.
Behavioral Patterns
Behavioral patterns are those patterns that are most specifically concerned with communication between objects. In this chapter, we?l see that:
The Observer pattern defines the way a number of classes can be notified of a change.
The Mediator defines how communication between classes can be simplified by using another class to keep all classes from having to know about each other.
The Chain of Responsibility allows an even further decoupling between classes, by passing a request between classes until it is recognized.
The Template pattern provides an abstract definition of an algorithm.
The Interpreter provides a definition of how to include language elements in a program.
The Strategy pattern encapsulates an algorithm inside a class,
The Visitor pattern adds function to a class, 
The State pattern provides a memory for a class? instance variables.
The Command pattern provides a simple way to separate execution of a command from the interface environment that produced it, and
The Iterator pattern formalizes the way we move through a list of data within a class.

The Singleton
Intent
1.    Ensure a class only has one instance, and provide a global point of access to it
Motivation
1.    Sometimes we want just a single instance of a class to exist in the system
2.    For example, we want just one window manager. Or just one factory for a family of products.
3.    We need to have that one instance easily accessible
4.    And we want to ensure that additional instances of the class can not be created
Structure 

 -------------------
| iSpooler       |
--------------------
| static Instance()| -------------- return unique instance
| finalize()       |
--------------------
| instance_flag    |
--------------------


class iSpooler
{
//this is a prototype for a printer-spooler class
//such that only one instance can ever exist
private static iSpooler instace;
//the constructor is privatized, 
//but need not have any content
private iSpooler() { }
//static Instance method returns one instance or null
static public iSpooler getInstance()
{
if (instance==null)
{
instance = new iSpooler();
}
return instance;
}
}


Do you fell satisfied enough with that? Or any else might be improved?
Unfortunately, in the example above, a thread may at any time pre-empt the call to getInstance(). For example, a thread may pre-empt a running thread at instance = new Singleton(). I f that were to happen, multiple Singleton instances might instantiate, thus defeating the purpose of a singleton.
To make a singleton thread safe, you have two choices. 
1.    The first simply synchronizes the getInstance() method:
public class Singleton {
    private static Singleton instance;
    private Singleton() {}
    public synchronized static Singleton getInstance() {
        if( instance == null ) {
            instance = new Singleton();
        }
        return instance;
    }
    public static void main( String [] args )
    {
        Singleton instance = Singleton.getInstance();
        // ...
    }
}    
2.    The second approach to thread safety declares a const ant Singleton attribute on the Singleton class itself:
public class Singleton {
    public final static Singleton instance =
new Singleton();
    
    private Singleton() {}
    public static void main( String [] args )
{
        Singleton instance =
Singleton.instance;
        // ...
    }
    
}
Reference:
Thinking in Patterns with Java, Revision 0.6 ?001 by Bruce Eckel
http://www.topica.com/lists/TIPatterns/
Patterns In Java Volume 1, copyright 1998 by Mark Grand
http://www.wiley.com/compbooks/
The Design Patterns Java Companion, Copyright ?1998, by James W. Cooper
Singlet ons with needles and thread, javaword Q&A
http://www.javaworld.com/javaworld/javaqa/2002-01/02-qa-0125-singleton4.html?
关闭本页
 
首页 | 投资与合作 | 服务条款 | 隐私政策 | 收藏本站 | 设为首页 | 新用户注册 | 免责声明 | 使用帮助
Copyright ©2005-2008 chinaitpower.com All rights reserved. www.chinaitpower.com 版权所有