singleton design pattern vs static class

공용 데이터를 저장하여 사용하고자 할 때, singleton design pattern이나 내부 static class를 사용한다.

싱글톤 패턴 (Singleton design pattern) -싱글톤 패턴이란 single instance object(해당 클래스의 인스턴스 하나)가 만들어지고, 어디서든지 그 싱글톤에 접근할 수 있도록 하기 위한 패턴

public final class SiteStructureSingletonPattern {
private Object[] data = new Object[10];
private static SiteStructureSingletonPattern instance = new SiteStructureSingletonPattern();

private SiteStructureSingletonPattern() {
System.out.println(“SiteStructureSingletonPattern constructor”);
for(int i=0; i<10; i++) {
data[i] = i+1;
}
}

public static SiteStructureSingletonPattern getInstance() {
return instance;
}

public void print() {
System.out.print(“SiteStructureSingletonPattern data=”);
for(int i=0; i<10; i++) {
System.out.print(” ” + data[i]);
}
System.out.println();
}
}

 

public class SiteStructureStaticClass {
private Object[] data = new Object[10];
private SiteStructureStaticClass() {
System.out.println(“SiteStructureStaticClass constructor”);
for(int i=0; i<10; i++) {
data[i] = i+1;
}
}

private static class SiteStructureStatic {
private static final SiteStructureStaticClass instance = new SiteStructureStaticClass();
}

public static SiteStructureStaticClass getInstance() {
return SiteStructureStatic.instance;
}

public void print() {
System.out.print(“SiteStructureStaticClass data=”);
for(int i=0; i<10; i++) {
System.out.print(” ” + data[i]);
}
System.out.println();
}
}

public class StaticClassSingletonPatternTest {

public static void main(String[] args) {
SiteStructureSingletonPattern instance = SiteStructureSingletonPattern.getInstance();
instance.print();
instance = SiteStructureSingletonPattern.getInstance();
instance.print();

SiteStructureStaticClass instance2 = SiteStructureStaticClass.getInstance();
instance2.print();
instance2 = SiteStructureStaticClass.getInstance();
instance2.print();
}

}

 

Static vs Instance Initializer Block

Static Initializer Block

  • class 로딩 시 호출
  • instance variable이나 method에 접근 못함
  • static variable 초기화에 사용

public class StaticIntializerBlockTest {
private static int id = 5;
static {
if (id <10) id = 20;
else id = 100;
}

public static int getId() {
return id;
}

public static void print()
{
System.out.println(“StaticIntializerBlockTest.id=” + getId());
}
}

public class StaticInstanceInitializerBlockTest {

public static void main(String[] args) {
StaticIntializerBlockTest.print();
}

}

StaticIntializerBlockTest.id=20 // static block 이 호출되면서 20으로 셋팅

Instance Initializer Block

  • 객체 생성시 호출
  • super 생성자 이후에 실행하고, 생성자보다 먼저 실행
  • instance variable이나 method에 접근 가능
  • 모든 생성자의 공통 부분을 instance initializer block에 넣어줌

class InstanceInitializerBlockSuper {
public InstanceInitializerBlockSuper() {
System.out.println(“InstanceInitializerBlockSuper”);
}
}

public class InstanceInitializerBlockTest extends InstanceInitializerBlockSuper {
private int id = 5;
{
if (id <10) id = 20;
else id = 100;
}

public InstanceInitializerBlockTest() {
System.out.println(“InstanceInitializerBlockTest.id=” + this.id);
}

public InstanceInitializerBlockTest(int id) {
System.out.println(“InstanceInitializerBlockTest.id=” + this.id);
this.id = id;
}

public int getId() {
return id;
}

public void print()
{
System.out.println(“StaticIntializerBlockTest.id=” + getId());
}

}

public class StaticInstanceInitializerBlockTest {

public static void main(String[] args) {
InstanceInitializerBlockTest i = new InstanceInitializerBlockTest();
i.print();
i = new InstanceInitializerBlockTest(30);
i.print();
}

}

InstanceInitializerBlockSuper // super 생성자 이후에 실행
InstanceInitializerBlockTest.id=20 // instance block 호출되면서 20으로 셋팅 
id=20
InstanceInitializerBlockSuper // super 생성자 이후에 실행
InstanceInitializerBlockTest.id=20 // instance block 호출되면서 20으로 셋팅된후 this.id = id를 통해서 30으로 셋팅
id=30

https://stackoverflow.com/questions/12550135/static-block-vs-initializer-block-in-java

Constructor usage guideline

private constructor는 정적 메소드와 필드 (static method & field)만 있는 경우 사용함.

class Counter {
private Counter() { }
public static int currentCount;
public static int IncrementCount() { return ++currentCount; }
}
class TestCounter
{
public static void main(String[] args)
{
// If you uncomment the following statement, it will generate
// an error because the constructor is inaccessible:
//Counter aCounter = new Counter(); // Error
Counter.currentCount = 100;
Counter.IncrementCount();
System.out.println(“count=” + Counter.currentCount);
}
}
// Output: New count: 101

protected constructor는 추상클래스 (abstract class)에서 사용을 권고함. 추상 클래스를 상속받는 파생클래스에서 파생 클래스 생성자가 부모 클래스 즉, 추상 클래스를 초기화 하기 위해 추상 클래스 생성자를 호출 할 수 있도록 지원함.

public abstract class Shape
{
protected Shape(String name) { this.name = name; }
private String name;
public void print() { System.out.print(this.name); }
}

public class Rectangle extends Shape
{
private double width, height;
public Rectangle(String name) { super(name); this.width = 2; this.height = 3; }
@Override
public void print()
{
super.print();
System.out.printf(” 가로: %f 세로: %f\n”, this.width, this.height);
}
}

public class Triangle extends Shape
{
private double bottom, height;
public Triangle(String name) { super(name); this.bottom = 1; this.height = 1; }
@Override
public void print()
{
super.print();
System.out.printf(” 밑변: %f 높이: %f\n”, this.bottom, this.height);
}
}

class ShapeTest
{
public static void main(String[] args)
{
//Shape s1 = new Shape(“도형”); // Error; Shape is abstract; cannot be instantiated
Shape s = new Triangle(“삼각형”);
s.print(); // 삼각형 밑변: 1 높이: 1
s = new Rectangle(“직사각형”);
s.print(); // 직사각형 가로: 2 세로: 3
}
}

default, public, protected, private

default (package private – access in other classes within the same package)

public (visible everywhere)

protected (only access in its own class, its subclass and other classes within the same package)

private (only access in its own class)

http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html

Access Levels
Modifier Class Package Subclass World
public Y Y Y Y
protected Y Y Y N
no modifier Y Y N N
private Y N N N

 

Break a loop if ‘q’ key is pressed

public static boolean getUserInputExitKey() {
System.out.println(“Please enter key to continue or the ‘q’ key to exit.”);
try {
if ((char)System.in.read() == ‘q’) return true;
}
catch (IOException e) {
System.out.println(“Error user key reading”);
}
return false;
}

//////////////////////////////////////////////////////////////////////////////////////////////

do {

// do whatever..

} while(!getUserInputExitKey());

Lab2

Lab2 프로젝트 디렉토리 안에 모든 파일(src/*.java & bin/*.class)와 보고서 (2~3장)를 넣고 Lab2_학번_이름.zip 압축한 후 e-learning(http://lms.dankook.ac.kr/index.jsp)으로 제출 ()

Lab2 – Basics (method, for, foreach, if, switch, do/while, while, array 활용)

수업블로그에 2.Basic 안에 TemperatureConverter 클래스 참고하여, 본인이 원하는 Converter 클래스를 추가작성한다 (예시: degree <-> radian 변환, kilometer <-> mile 변환,  kilogram <-> pound 변환, 등등).

http://www.unitconverters.net/

Object-Oriented Programming (OOP)

Object − objects have states and behaviors.
Class – defines the grouping of data and code, the “type” of an object
Instance – a specific allocation of a class
Message – sent to objects to make them act
Method – a “function” that an object knows how to perform
Local Variables − variables defined inside methods, constructors or blocks
Instance Variables – variables within a class but outside any method (a specific piece of data belonging to an object)
Class Variables − variables declared within a class, outside any method, with the static keyword
Encapsulation – keep implementation private and seperate from interface
Polymorphism – different objects, same interface
Inheritance – hierarchical organization, share code, customize or extend behaviors