습관제작소

23-02-06 JAVA (클래스와 객체 - static의 응용 싱글톤 패턴) 본문

Programing Language/JAVA STUDY

23-02-06 JAVA (클래스와 객체 - static의 응용 싱글톤 패턴)

KUDO 2023. 2. 6. 13:51

싱글톤 패턴이란

디자인 패턴

연습문제

  • singleton01

package ex;

public class singleton01 {
    private String name;
    private int kor;
    private int eng;

    private static singleton01 instance=new singleton01();
    private singleton01() {}

    public static singleton01 getLnstance() {
        if(instance==null) {
            instance=new singleton01();
        }
        return instance;
    }

    void setTot(int kor, int eng) {
        this.kor = kor;
        this.eng = eng;
    }
    int gettot() {
        int tot = kor+eng;
        return tot;
    }

    void setSubject() {
        System.out.println("국어 : "+kor+"영어 : "+eng);
    }

}

  • singleton01Example

package ex;

import java.util.Scanner;

public class singleton01Example {
    public static void main(String[] args) {

        int kor;
        int eng;
        singleton01 mySingleton = singleton01.getLnstance();

        Scanner sc = new Scanner(System.in);

        System.out.println("국어 점수 : ");
        kor = sc.nextInt();
        System.out.println("영어점수 : ");
        eng = sc.nextInt();

        mySingleton.setTot(kor, eng);
        int tot = mySingleton.gettot();
        mySingleton.setSubject();
        System.out.println(tot);
    }    

}

'Programing Language > JAVA STUDY' 카테고리의 다른 글

23-02-07 JAVA (객체 배열, 배열 복사)  (0) 2023.02.07
22-05-26 JAVA (JDBC - 회원 가입)  (0) 2022.05.29
22-05-23 JAVA Sort_Binery  (0) 2022.05.23
22-05-23 JAVA Sort_Selection  (0) 2022.05.23
22-05-20 JAVA 객체 (MP3)  (0) 2022.05.20
Comments