模板方法模式,策略模式
阿新 • • 發佈:2019-02-12
1策略模式:
實現一個程式,電影票打折,老人,小孩各有不同的折扣看電影。
2:模板方法模式public class Test1 { public static void main(String[] args) { // TODO Auto-generated method stub People p =new OldPeople("老人"); p.buyTickets(); p.getDiscount(new DiscontOf5()); } } interface Discount{ public void discountWay(); } class DiscontOf7 implements Discount{ public void discountWay(){ System.out.println("電影票打七折"); } } class DiscontOf5 implements Discount{ public void discountWay(){ System.out.println("電影票打五折"); } } class DiscontOf8 implements Discount{ public void discountWay(){ System.out.println("電影票打八折"); } } abstract class People{ private String typePeople; private Discount discount; public People(String typePeople){ this.typePeople=typePeople; } public void getDiscount(Discount discount){ discount.discountWay(); } public void buyTickets(){ System.out.println(typePeople+"買票看電影!"); } } class OldPeople extends People{ public OldPeople(String typePeople){ super(typePeople); } }
實現一個程式,去飯店吃飯,選擇各種不同的套餐。
public class Test { public static void main(String[] args) { // TODO Auto-generated method stub PersonTreat personA=new PersonA("張三"); personA.treat(); personA.dishes(); personA.payment(); } } abstract class PersonTreat{ protected String name; public void treat(){ System.out.println(name+"要請客吃飯"); } public void dishes(){ switch (change()) { case 1: System.out.println("點的菜有:宮保雞丁,紅燒排骨。。。。。"); break; case 2: System.out.println("點的菜有:魚香肉絲,鐵板魷魚。。。。。"); break; case 3: System.out.println("點的菜有:碳烤活魚,水煮魚片。。。。。"); break; default: System.out.println("不知道怎麼選擇。"); break; } } public void payment(){ System.out.println(name+"結賬"); } abstract int change(); } class PersonA extends PersonTreat{ public PersonA(String name) { this.name=name; } public int change(){ Random r =new Random(); int a =r.nextInt(3)+1; return a; } }