Rumah >Java >javaTutorial >templat
Templat ialah salah satu corak reka bentuk tingkah laku, kelas abstrak mentakrifkan satu set cara/templat untuk melaksanakan kaedahnya.
Subkelasnya boleh mengatasi/melaksanakan kaedah ini tetapi seruannya hendaklah dengan cara yang sama seperti yang ditakrifkan oleh kelas abstrak
Mari kita fahami ini dengan contoh:
Konsep utama
Templat: Kelas abstrak yang mentakrifkan struktur/cara/templat algoritma
Pelaksanaan Konkrit: Pelaksanaan Konkrit Templat
Pelanggan: Pelanggan yang akan menggunakan Templat ini
public abstract class Gametemplat{ //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 Gametemplat{ @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 Gametemplat{ @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 Gametemplat football = new Football(); football.play();// play() will strictly follow the sequence of method execution defined in the final play() method Gametemplat cricket = new Cricket(); cricket.play(); } }
Output:
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
nota: Kod mengikut semua prinsip reka bentuk seperti LSP, ISP, SRP, OCP
Atas ialah kandungan terperinci templat. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!