> Java > java지도 시간 > 본문

주형

Linda Hamilton
풀어 주다: 2024-09-22 22:16:02
원래의
481명이 탐색했습니다.

주형

템플릿은 동작 디자인 패턴 중 하나이며 추상 클래스는 해당 메서드를 실행하는 방법/템플릿 집합을 정의합니다.

하위 클래스는 이러한 메서드를 재정의/구현할 수 있지만 호출은 추상 클래스에서 정의한 것과 동일한 방식으로 이루어져야 합니다

예를 들어 이해해 보겠습니다.

핵심 개념
템플릿: 알고리즘의 구조/방식/템플릿을 정의하는 추상 클래스
구체적인 구현: 템플릿의 구체적인 구현
클라이언트: 이 템플릿을 사용할 클라이언트

public abstract class Game주형{
    //these below methods can be overridden based on the type of game
    public abstract void initialize();
    public abstract void startPlay();
    public abstract void  endPlay();

    //All the subclasses must use this same method to play the game i.e. following the same template present in this method,
    //Hence it is declared as final.
    public final void play(){
        initialize();
        startPlay();
        endPlay();
    }
}

public class Cricket extends Game주형{


    @Override
    public void initialize(){
        System.out.println("Cricket has been initialized");
    }
    @Override
    public void startPlay(){
        System.out.println("Cricket game has been started");
    }
    @Override
    public void endPlay(){
        System.out.println("Cricket game has ended");
    }

}

public class Football extends Game주형{

    @Override
    public void initialize(){
        System.out.println("Football has been initialized");
    }
    @Override
    public void startPlay(){
        System.out.println("Football game has been started");
    }
    @Override
    public void endPlay(){
        System.out.println("Football game has ended");
    }

}

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

        //Create a football game object 
        Game주형 football = new Football();
        football.play();// play() will strictly follow the sequence of method execution defined in the final play() method

        Game주형 cricket = new Cricket();
        cricket.play();
    }
}

로그인 후 복사

출력:

Football has been initialized
Football game has been started
Football game has ended
Cricket has been initialized
Cricket game has been started
Cricket game has ended
로그인 후 복사

참고: 코드는 LSP, ISP, SRP, OCP와 같은 모든 설계 원칙을 따릅니다

위 내용은 주형의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
저자별 최신 기사
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!