Can anybody tell me a good example o开发者_JAVA百科f Singleton pattern? Also I've one doubt to ask, Is the following scenario is that of singleton pattern:
When we have many printers connected in LAN but only one printer queue?
Singleton is a software pattern.
Here is an example in C#.
Having a single queue on a LAN is more of a hardware/network design issue rather than a software concept, so not really applicable. If you were modeling such a thing in software and had to be certain there is only one queue, then it would be applicable.
My personal rule for using singletons is that only get used when it's an error for there to be more than one instance, and global access is required. I would say that a print queue is therefore not a good candidate for singleton: because you don't need global access, and it's also arguable that it's an error to have more than one. In fact, while there may be one "physical" print queue (e.g. on a print server somewhere) that's not what the application cares about, it just needs to submit "jobs":
PrintJobScheduler pjs;
pjs.SubmitPrintJob(myPrintJob);
You don't need my imaginary PrintJobScheduler
to be a singleton, even though it may be talking to a "singleton" service somewhere on the network.
The general idea behind a singleton is that it is an object for which it makes no sense to have more than one, and which may need to be accessed all over your program.
The one I end up using all the time is a program configuration.
A typical one of my configuration singletons will contain things like IP addresses, device names, and system limits. When first called, it will typcially read a configuration file (sometimes and/or the system registry on Windows), and load in default values for items not found there. It really makes no sense for a program to have multiple configurations, so all this stuff should just be read in once for the entire program. Additionally, configuration items may need to be accessed by all kinds of different otherwise unrelated classes in the system.
In game design, if you have a graphics device handle or similar hardware abstraction that's responsible for a single resource like rendering or audio, then it should be a singleton.
At least that's what I was told.
class Singleton
{
#region Subj Implementation
private Singleton() { }
private static readonly Lazy<Singleton> _lazyInit = new Lazy<Singleton>
(() => new Singleton());
public static Singleton Instance { get { return _lazyInit.Value; } }
#endregion
}
An HTTP response might be a good example. You don’t want to have two or more instances sending contradicting headers.
if i have lots of movies in one folder i select all and press enter then more than one instances of player(which you are using e.g media player) are created which results in using of resourses so thereshould be singelton design pattern to create only one instance.
Singleton pattern controls the object creation. It guarantees that at any given point of time only 1 object is present. It is easier to implement but can be dangerous.
- GC of such objects is difficult.
- Difficult to test
I do not think printer queue is a singleton pattern.
One of the best examples (in real life) of the Singleton pattern that I've seen is SQL Connection Pooling in .NET.
If you want to see the code, you'll have to pop open Reflector...but the Singleton keeps track of all the available connections and hands them out as they're available.
As for your example, it's a little vague. The document queue on each individual printer might be a better example. As documents come to the printer, they are put in the queue. Each process running on the printer then grabs a document from the Singleton queue (rather than creating its own queue for its thread).
Singleton pattern is the simplest pattern in java and is under the creational pattern. some key points to use in singleton pattern.
- It is static in nature
- private constructor
- private static instance of the class
- public static getter method
- no parameters to the constructor
create singleton class
public class Singleton {
private static Singleton object = null;
private Singleton() {
}
public static Singleton getInstance() {
if (object == null) {
object = new Singleton();
}
return object;
}
public void showMessage() {
System.out.println("Singleton Pattern");
}
}
create demo class
public class Demo {
public static void main(String[] args) {
Singleton object = Singleton.getInstance();
object.showMessage();
}
}
but this classic implementation not thread safe. therefore using synchronized make sure that the one thread can execute the getInstance();
at one time.
As this;
public class Singleton {
private static Singleton object = null;
private Singleton() {
}
public static synchronized Singleton getInstance() {
if (object == null) {
object = new Singleton();
}
return object;
}
}
Here is example code of 4 of the 5 possible singleton Types suggested at: http://javabeat.net/spring-singleton-java-singleton/
// Java code for Bill Pugh Singleton Implementaion
class GFG
{
private GFG() {}
private static class BillPughSingleton
{
private static final GFG INSTANCE = new GFG();
}
public static GFG getInstance()
{
// loads instance of inner class lazily instead of needing to check for null
return BillPughSingleton.INSTANCE;
}
}
// Singleton Handling Exception
class HFH
{
public static HFH INSTANCE;
private HFH() { }
static {
INSTANCE = new HFH();
}
}
// double check locking
class DCL
{
private static DCL INSTANCE;
private DCL() { }
public static DCL getInstance()
{
if (INSTANCE == null)
{
//synchronized block to remove overhead from sychronizing method
synchronized (DCL.class)
{
if(INSTANCE==null)
{
INSTANCE = new DCL();
}
}
}
return INSTANCE;
}
}
enum EnumSingleton {
INSTANCE("Instance Text");
private String info;
private EnumSingleton(String info) {
this.info = info;
}
public EnumSingleton getInstance() {
return INSTANCE;
}
@Override
public String toString() {
return info;
}
}
class Main {
public static void main(String... args) {
GFG bps = GFG.getInstance();
System.out.println(bps);
HFH hfh = HFH.INSTANCE;
System.out.println(hfh);
DCL dcl = DCL.getInstance();
System.out.println(dcl);
EnumSingleton es = EnumSingleton.INSTANCE;
System.out.println(es.toString());
System.out.println("Done.");
}
}
class singleton{
public static singleton obj = null;
protected singleton(){ }
public static singleton getObj(){
if(obj == null){
obj = new singleton();
}
return obj;
}
}
public class First {
public static void main(String[] args) {
singleton ss = singleton.getObj();
}
}
精彩评论