Skip to content

Commit ef82b3a

Browse files
committed
singleton
1 parent 22a03c5 commit ef82b3a

File tree

3 files changed

+49
-0
lines changed

3 files changed

+49
-0
lines changed

src/main/java/helloworld/Main.java

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
import helloworld.creational.builder.HelloWorldBuilder;
66
import helloworld.creational.factory_method.FactoryMethodHelloWorldFactory;
77
import helloworld.creational.prototype.HelloWorldPrototype;
8+
import helloworld.creational.singleton.HelloWorldSingleton;
89

910
/**
1011
* @author yihua.huang@dianping.com
@@ -35,5 +36,8 @@ public static void main(String[] args) throws InstantiationException, IllegalAcc
3536
HelloWorld prototypeHelloWorld = HelloWorldPrototype.PROTOTYPE.clone();
3637
System.out.println(prototypeHelloWorld.helloWorld());
3738

39+
HelloWorld singletonHelloWorld = HelloWorldSingleton.instance();
40+
System.out.println(singletonHelloWorld.helloWorld());
41+
3842
}
3943
}
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
package helloworld.creational.singleton;
2+
3+
import helloworld.HelloWorld;
4+
5+
/**
6+
* @author yihua.huang@dianping.com
7+
*/
8+
public class HelloWorldSingleton implements HelloWorld {
9+
10+
@Override
11+
public String helloWorld() {
12+
return "Hello Singleton!";
13+
}
14+
15+
public static HelloWorldSingleton instance() {
16+
return HelloWorldSingletonInner.INSTANCE;
17+
}
18+
19+
private HelloWorldSingleton() {
20+
21+
}
22+
23+
static class HelloWorldSingletonInner {
24+
private static final HelloWorldSingleton INSTANCE = new HelloWorldSingleton();
25+
}
26+
27+
}
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
package helloworld.creational.singleton;
2+
3+
import helloworld.HelloWorld;
4+
import org.junit.Test;
5+
import static org.hamcrest.MatcherAssert.assertThat;
6+
import static org.hamcrest.Matchers.is;
7+
8+
/**
9+
* @author yihua.huang@dianping.com
10+
*/
11+
public class HelloWorldSingletonTest {
12+
13+
@Test
14+
public void testHelloWorldSingleton(){
15+
HelloWorld helloWorld = HelloWorldSingleton.instance();
16+
assertThat(helloWorld.helloWorld(),is("Hello Singleton!"));
17+
}
18+
}

0 commit comments

Comments
 (0)