<조건> 1. 반드시 static키워드가 붙은 자료형이 내 자신의 클래스인 속성 하나가 선언되어야 한다.
package two; public class Student { private int hakno; private Student(){} public staticStudentgetInstance(){ if(stu=null) stu = new Student(); return stu; } public void setHakno(int hakno){ this.hakno=hakno; } public int getHakno {return hakno;} }
2. 반드시 생성자들의 접근제어자가private으로 처리 되어야 한다. 싱글톤패턴에 맞게끔 외부에서 객체생성을 못하도록 접근 제한.
package one; public class Ex01 { public static void main(String[] args) { Student st1 = Student.getInstance(); //&100 Student st2 = Student.getInstance(); //&100 } }
3. 반드시 1번의 필드를 반환해주는 public static이 붙은 geter method가 존재해야한다.
public static void getIns(){ if(stu=null) stu = new Student(); return new Student(); }
Company.java
package singleton;
public class Company {
// private static Company instance = new Company ();
private static Company instance;
private Company () {}
public static Company getInstance() {
if(instance==null) {
instance = new Company();
}
return instance;
}
}
package singleton;
public class CompanyTest {
public static void main(String[] args) {
Company myCompany1 = Company.getInstance();
Company myCompany2 = Company.getInstance();
System.out.println( myCompany1 == myCompany2 );
}
}
true
변수들의 생명주기
변수들의 생명주기
탄생
죽음
local 변수
지역변수가 선언된 시점
지역변수가 포함된 메소드나 생성자의 명령이 종료된 후
instance변수
객체가 선언된 시점
인스턴스가 소멸되는 시점
class Ex { int a ; public void md(){ this.a a= a; } public int getmd(){ return a; } }
class ExMain{ public static void main(String[] args){ Ex e = new Ex(); e.a = a; } }
static(=class, 정적)
클래스가 메모리에 올라가는 시점 (=프로그램이 실행되는 시점)
프로그램이 종료되는 시점
통합 모델링언어 UML(Unifed Modeling Language)
: 개발자가 필요한 요소들 정리, 요소들의 관계 정의, 요소들간의 흐름들을 도식화할때 사용하는 다이어그램
[접근제어자][기타제어자]자료형 변수명; + public final {readOnly} # protected static___ ~ default - private
클래스 다이어그램
: 클래스, 인터페이스, 추상클래스들 안에 필요한 속성, 기능 정리, 조건정리, 해당 요소들 간의 관계정리
기술 순서
코드
다이어그램
클래스명
스테레오타입기술 : 추상클래스명, 인터페이스명
class Ex
<<interface>> Ex
속성
변수 상수 객체
접근제어자기호 속성명 : 자료형 {옵션} static 나타내는 밑줄
public final int MAX = 5; private static String str;