设计模式之 登记式单例类,最原形的代码,个人感觉对学习很有用,贴上来
viewsource
print?01 | import java.util.HashMap; |
02 | public class RegSingleton |
04 | static private HashMap
m_registry = new HashMap(); |
07 | RegSingleton
x = new RegSingleton(); |
08 | m_registry.put(
x.getClass().getName() , x); |
13 | protected RegSingleton()
{} |
17 | static public RegSingleton
getInstance(String name) |
21 | name
= "com.javapatterns.singleton.demos.RegSingleton" ; |
23 | if (m_registry.get(name)
== null ) |
28 | Class.forName(name).newInstance()
) ; |
32 | System.out.println( "Error
happened." ); |
35 | return (RegSingleton)
(m_registry.get(name) ); |
42 | return "Hello,
I am RegSingleton." ; |
46 | 它的子类RegSingletonChild
需要父类的帮助才能实例化。请看下面的相关代码: |
49 | import java.util.HashMap; |
50 | public class RegSingletonChild extends RegSingleton |
52 | public RegSingletonChild()
{} |
56 | static public RegSingletonChild
getInstance() |
58 | return (RegSingletonChild) |
59 | RegSingleton.getInstance( |
60 | "com.javapatterns.singleton.demos.RegSingletonChild" ); |
67 | return "Hello,
I am RegSingletonChild." ; |
71 | /*********************************一个子类实现的范例**************************/ |
72 | import java.util.HashMap; //使用了哈希映射的相关方法 |
73 | public class RegSingletonChild extends RegSingleton
{ |
74 | public RegSingletonChild()
{} |
76 | static public RegSingletonChild
getInstance() { |
77 | return (RegSingletonChild) |
78 | RegSingleton.getInstance( "com.javapatterns.singleton.demos.RegSingletonChild" ); |
81 | public String
about() { |
82 | return "Hello,
I am RegSingletonChild." ; |
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理