`
DavyJones2010
  • 浏览: 151822 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

DesignPattern : Singleton

阅读更多

1. Eager Initialization Approach

package edu.xmu.designPattern.DesingPattern_Singleton;

public class Singleton
{
	private static Singleton singleton = new Singleton();

	private Singleton()
	{
	}

	public static Singleton getInstance()
	{
		return singleton;
	}
}
package edu.xmu.designPattern.DesingPattern_Singleton;

import static org.junit.Assert.assertEquals;

import org.junit.Test;

public class AppTest
{
	@Test
	public void test()
	{
		Singleton singleton1 = Singleton.getInstance();
		Singleton singleton2 = Singleton.getInstance();

		assertEquals(singleton1, singleton2);
	}
}

 

2. Lazy Initialization Approach

package edu.xmu.designPattern.DesingPattern_Singleton;

public class Singleton
{
	private static Singleton singleton = null;

	private Singleton()
	{
	}

	public static Singleton getInstance()
	{
		if (null == singleton)
		{
			singleton = new Singleton();
		}
		return singleton;
	}
}
package edu.xmu.designPattern.DesingPattern_Singleton;

import static org.junit.Assert.assertEquals;

import org.junit.Test;

public class AppTest
{
	@Test
	public void test()
	{
		Singleton singleton1 = Singleton.getInstance();
		Singleton singleton2 = Singleton.getInstance();

		assertEquals(singleton1, singleton2);
	}
}

    Comments:

        1) Problems may occur when under the circumstance of multi-thread.

package edu.xmu.designPattern.DesingPattern_Singleton;

public class Singleton
{
	private static Singleton singleton = null;

	private Singleton()
	{
	}

	public static Singleton getInstance()
	{
		if (null == singleton)
		{
			try
			{
				System.out.println("Current Thread: " + Thread.currentThread());
				Thread.sleep(1000);
			} catch (InterruptedException e)
			{
				e.printStackTrace();
			}
			singleton = new Singleton();
		}
		return singleton;
	}
}
package edu.xmu.designPattern.DesingPattern_Singleton;

public class AppTest
{
	public static void main(String[] args)
	{
		new MyThread().start();
		new MyThread().start();
	}

}

class MyThread extends Thread
{
	private Singleton singleton = null;

	@Override
	public void run()
	{
		singleton = Singleton.getInstance();
		System.out.println(singleton);
	}
}

 

Current Thread: Thread[Thread-0,5,main]
Current Thread: Thread[Thread-1,5,main]
edu.xmu.designPattern.DesingPattern_Singleton.Singleton@1b67f74
edu.xmu.designPattern.DesingPattern_Singleton.Singleton@69b332

    Comments:

        1) We can find out that there has been two different instance of Singleton created.

            This violates Singleton.

        2) We can use getInstance() to mark that we are using Singleton.

            We can use newInstance() to mark that we are using Reflection to create a new instance.

 

3. Enum Approach

package edu.xmu.oop.singleton;

public enum Singleton {
    SINGLETON("Davy", 24);

    private String name;
    private int age;

    Singleton(String name, int age) {
	this.name = name;
	this.age = age;
    }

    public String getName() {
	return this.name;
    }

    public int getAge() {
	return this.age;
    }

    public void setName(String name) {
	this.name = name;
    }

    public void setAge(int age) {
	this.age = age;
    }

    @Override
    public String toString() {
	return "name: " + name + ", age: " + age;
    }

}
package edu.xmu.oop.singleton;

import static org.junit.Assert.assertEquals;

import org.apache.log4j.Logger;
import org.junit.Test;

public class SingletonTest {
    private static final Logger logger = Logger.getLogger(SingletonTest.class);

    @Test
    public void singletonTest() {
	Singleton instance = Singleton.valueOf("SINGLETON");
	logger.info(instance.toString());
	assertEquals("name: Davy, age: 24", instance.toString());

	instance = Singleton.SINGLETON;
	logger.info(instance.toString());
	assertEquals("name: Davy, age: 24", instance.toString());

	instance.setName("Cal");
	instance.setAge(22);
	logger.info(instance.toString());
	assertEquals("name: Cal, age: 22", instance.toString());

	instance = Singleton.valueOf("SINGLETON");
	logger.info(instance.toString());
	assertEquals("name: Cal, age: 22", instance.toString());
    }
}

  Advantages:

       1> Thread safe: Enum is thread safe and implementation of Singleton through Enum ensures that your singleton will have only one instance even in a multithread env.

       2> Deserialization safe: When we serialize a class and deserialize it then it creates another instance of the singleton class. Basically as many times as you deserialize the singleton instance,

            it will create multiple instance. In this case, the best way is to make the singleton as enum, in that way, the underlying Java implementation takes caare of all the details,

            if this is not  possible when we will need to override the readobject() method to return the same singleton instance.

    Disadvantates:  

        1> Enum instance is defined at compile time, we cannot make any changes to the properties of this instance if the properties are final.

             These properties are assigned with default value before we can even have access to that.

 

Conclusion: 

    A single-element enum type is the best way to implement a singleton.

 

Reference Links:

1) Effective Java 2nd Edition -Joshua Blosh

2) http://java.dzone.com/articles/singleton-design-pattern-%E2%80%93

3) http://stackoverflow.com/questions/18882612/is-it-possible-to-have-a-java-singleton-using-an-enum-that-uses-constructor-argu

 

分享到:
评论

相关推荐

    DesignPattern:设计模式样本

    "DesignPattern:设计模式样本"这个项目可能包含了各种设计模式的实现示例,特别是对Java中的Singleton模式进行了深入探讨。 Singleton模式是一种创建型设计模式,它确保一个类只有一个实例,并提供一个全局访问点。...

    DesignPattern::pencil:设计模式_java实现以及详解

    本资源“DesignPattern::pencil:设计模式_java实现以及详解”提供了一套详细的学习材料,帮助开发者理解和应用设计模式。 该资源的作者是“养码青年-Style”,他通过这个项目记录了自己的设计模式学习过程。鼓励...

    DesignPattern:C#设计模式示例

    "DesignPattern:C#设计模式示例"这个资源很可能是包含多个C#实现的设计模式示例代码库。 设计模式通常分为三类:创建型、结构型和行为型。每种模式都解决了特定场景下的问题,并提供了良好的代码组织和扩展性。 ...

    FOAD-DesignPattern:FOAD-DesignPattern

    2. 单例模式(Singleton Pattern): 单例模式确保一个类只有一个实例,并提供一个全局访问点。在C#中,通常通过私有构造函数和静态方法来实现单例,确保类的唯一性。单例模式常用于控制资源的共享,如数据库连接、...

    design pattern

    在给定的压缩包文件中,包含了九种经典的设计模式示例,它们分别是:单例模式(Singleton)、策略模式(StrategyPattern)、适配器模式(AdapterPattern)、装饰者模式(DecoratorPattern)、抽象工厂模式...

    designpattern:Head First 设计模式练习

    private static Singleton instance = new Singleton(); private Singleton() {} public static Singleton getInstance() { return instance; } } ``` 接着,工厂模式(Factory Method)用于创建对象,它提供...

    DesignPattern_Singleton:csdb博客设计模式(1)_单例模式原始码

    在CSDN博客中的"DesignPattern_Singleton:csdb博客设计模式(1)_单例模式原始码",博主详细探讨了如何在C#中实现单例模式。 单例模式的核心思想在于限制类的实例化,防止通过常规构造函数创建多个实例。通常,我们...

    DesignPattern:设计模式小Demo

    设计模式是软件工程中的一种最佳实践,用于解决在软件设计中常见的...以上就是这个DesignPattern小Demo中可能会涵盖的设计模式,通过这些模式的实例,你可以更好地理解和应用它们到实际项目中,提升你的Java编程能力。

    DesignPattern:来自 http 的设计模式参考

    在"DesignPattern-master"这个压缩包中,可能包含了这些模式的Java实现示例,以及相关的解释和用法说明。通过学习和应用这些模式,开发者可以提高代码质量,降低维护成本,并提升软件系统的可扩展性。对于任何Java...

    DesignPattern:有关设计模式的一些演示

    这个名为"DesignPattern:有关设计模式的一些演示"的项目,可能是为了帮助开发者理解和应用各种设计模式。 设计模式分为三大类:创建型、结构型和行为型。创建型模式关注对象的创建过程,如单例(Singleton)、工厂...

    DesignPattern:设计模式.net源代码

    本资源"DesignPattern:设计模式.net源代码"提供了一套基于.NET实现的设计模式示例,旨在帮助程序员更好地理解和应用这些模式。 在"DesignPattern-master"这个压缩包中,你可能找到的文件结构和内容包括: 1. **...

    DesignPattern:设计模式

    DesignPattern-master这个压缩包可能包含了一个关于设计模式的项目或者教程资源。 设计模式分为三类:创建型模式(Creational Patterns)、结构型模式(Structural Patterns)和行为型模式(Behavioral Patterns)...

    designPattern:设计模式相关代码实现

    "designPattern:设计模式相关代码实现"这个项目,显然提供了不同设计模式在Java语言中的实际应用示例。 在Java世界里,设计模式主要分为三大类:创建型模式、结构型模式和行为型模式。每种模式都针对特定的编程问题...

    DesignPattern:设计模式演示程序

    这个名为"DesignPattern"的压缩包文件很可能包含了一个Java实现的各种设计模式的示例程序。 在这个"DesignPattern-master"目录中,我们可以期待找到一系列与设计模式相关的Java源代码文件(.java),每个文件或...

    designPattern:코딩사전님의정정정리

    "designPattern:코딩사전님의정정정리"可能是某位名为"정정전"的专家或教师对设计模式进行整理和修正后的资料集合,旨在帮助开发者更好地理解和应用这些模式。 首先,设计模式分为三大类:创建型、结构型和行为型...

    Design Pattern英文版

    设计模式(Design Pattern)是软件工程中的一种经验总结,它是在特定上下文中为解决常见问题而提出的一套可复用的解决方案。设计模式并不直接实现为代码,而是提供了一种在面向对象设计中如何处理常见问题的指南。...

    阅读java源码-JavaDesignPattern:23种设计模式Java实现

    在“阅读java源码-JavaDesignPattern:23种设计模式Java实现”中,我们将深入探讨这23种设计模式的Java实现。 1. **创建型模式**(Creational Patterns): - **单例模式(Singleton)**:确保一个类只有一个实例,...

    Java-DesignPattern:Java中23种常见的设计模式

    本资料包“Java-DesignPattern:Java中23种常见的设计模式”涵盖了软件设计中的重要概念,以下是这些模式的详细说明: 1. **单例模式(Singleton)**:确保一个类只有一个实例,并提供全局访问点。防止其他对象多次...

    DesignPattern:关于设计模式

    在这个“DesignPattern”仓库中,可能包含了对各种设计模式的详细解释、示例和应用。 设计模式分为三大类:创建型、结构型和行为型模式。创建型模式主要关注对象的创建过程,如单例模式(Singleton)、工厂模式...

Global site tag (gtag.js) - Google Analytics