package day08.static_.method;
public class Count {
public int a;
public static int b;
//일반메서드 - 일반변수, 정적변수 둘다 사용가능
public int some1() { //일반이라 일반변수 가능
a = 10; //ok
return ++b; //ok
}
//정적메서드 - 정적변수만 사용가능(단, 객체생성을 통해서는 사용이 가능)
public static int some2() {
//a = 10; //no - 정적 메서드라 정적만 가능(아니면 객체만들어서 불러오기
Count c = new Count();
c.a = 10;//ok
return ++b; //ok
}
}
메인
package day08.static_.method;
public class MainClass {
public static void main(String[] args) {
Count c = new Count();
c.some1(); //일반메서드
c.some2(); //정적메서드
//정적메서드 - 객체생성 없이 사용 (단,static 끼리만~!)
Count.some2();
//현재 b는 ? 3
//main은 static! 그래서 지금껏 객체생성해서 접근했던것
a();
// Math.random();
//
// Arrays.toString();
}
public static void a() {
}
}
package day08.static_.singleton;
public class Computer {
public static int a = 10;
//정적초기화자 - 1회만 실행됨
static {
System.out.println("단 1번 실행 - 클래스명이 호출될 때");
}
}
메인
package day08.static_.singleton;
public class MainClass {
public static void main(String[] args) {
System.out.println(Computer.a);
System.out.println(Computer.a);
System.out.println(Computer.a);
System.out.println(Computer.a);
4번실행해도 딱 1번 실행
}
}
싱글톤 패턴(singleton pattern)
싱글톤 클래스
package day08.static_.singleton;
public class Singleton {
//디자인패턴 - 클래스를 설계하는 기법
//싱글톤패턴 - 객체를 1개만 생성되도록 설계하는 기법
//1.나 자신의 객체를 멤버변수로 선언하고,1개로 고정한다.
private static Singleton instance = new Singleton();
//2.객체생성을 못하도록 생성자를 private처리
private Singleton() {} //메인에서 객체생성 불가!
//3. s변수(나자신객체)를 getter로 반환
// static 키워드를 붙임
// public 반환유형 이름() {
// }
public static Singleton getInstance(){
return instance;
}
public String site = "aaa";
}
package day08.static_.singleton;
public class MainClass {
public static void main(String[] args) {
//멤버에 static 없으면 무한루프
// Singleton instance = new Singleton();
Singleton s = Singleton.getInstance();
Singleton s2 = Singleton.getInstance();
Singleton s3 = Singleton.getInstance();
System.out.println(s == s2 && s2 == s3);
//s의 위치와 site위치가 똑같기때문에.. site가 static이 아니어도 값이 바뀐다.
s.site = "이순신";
System.out.println(s2.site);
System.out.println(s3.site);
}
}