Java资源网

| JAVA基础 | 环境配置 | JDBC | 线程技术 | Socket编程 | JavaMail | JAVA与XML | 设计模式 | 技术新闻 | Java认证 | 程序人生 软件下载
| JSP&Servlet | Spring | Struts | Hibernate | JBuilder | Eclipse | WebService | EJB技术 | J2ME开发 | 应用服务器 | JXTA | Ajax
Articles search文章搜索
   关键字:
   类 别:
       
New download 最新下载
· [组件]HTML Parser 1.5
· [教程]WebSphere Studio应用教程
· [组件]JDom 1.0
· [工具]Junit3.8.1
· [教程]EJB编程及J2EE系统架构和设计
· [教程]EJB教程
· [教程]J2EE Tutorial中文版
· [教程]Java编程思想2(英文)
· [教程]java编程思想(完整版)
· [教程]Java网络编程
New articles 最新文章
· 设计移动 Web 服务
· 解析XML的时候完全忽略DTD
· 理解XML Schema XML Schema 初步
· 标签库的深入研究
· 提升JSP应用程序的七大绝招
· 如何使用JDOM对XML文件进行操作
· 处理XML字符串中特殊字符
· 利用Digester把XML转换成为Java对象
· 使用WebService 和RMI远程协作
· 使用Axis开发Web Service程序
Articles top 热门文章
· Eclipse基础--plugin插件安装(6644)
· eclipse+tomcat+lomboz的安装配置说明(4774)
· Java程序员就业前景(4584)
· Windows下JAVA环境变量的设置祥解(3788)
· Tomcat下JSP、Servlet和JavaBean环境的配置(3716)
· 使用links方式安装Eclipse插件(3698)
· 一个老程序员的心理话(3533)
· linux下jdk的安装与配置(3459)
· 初学者入门:Structs中基本配置入门(3334)
· Eclipse 运行命令行参数大全(3084)
您的位置:首页>>设计模式>>[Creationalnbsp;Patterns]nbsp;Thenbsp;Singleton
[Creationalnbsp;Patterns]nbsp;Thenbsp;Singleton
2007-04-13   来源:www.javaresearch.org  作者:未知

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?


  --相关文章--
· 面向对象编程,我的思想 (2007-04-13)
· 面向对象的思维方式 (2007-04-13)
· 通过Javanbsp;Swing看透MVC设计模式 (2007-04-13)
· 适配器模式(Adapternbsp;Pattern) (2007-04-13)
· 追MM与Java的23种设计模式 (2007-04-13)
· 责任链模式(Chainnbsp;ofnbsp;Responsibility) (2007-04-13)

版权所有©2005-2006 JAVA资源网 渝ICP备05007591号 虚拟主机 | 关于我们 | 联系方式 | 广告业务 | 网站地图 | 友情链接