测试类:
1 public class Test { 2 3 public static void main(String[] args) { 4 5 Person man = new Man(); 6 7 Person lady = new Lady(); 8 9 Clothing jacket = new Jacket(); 10 11 Clothing trouser = new Trouser(); 12 13 jacket.personDressCloth(man); 14 trouser.personDressCloth(man); 15 16 jacket.personDressCloth(lady); 17 trouser.personDressCloth(lady); 18 } 19 }1 public abstract class Person { 2 3 private Clothing clothing; 4 5 private String type; 6 7 public Clothing getClothing() { 8 return clothing; 9 } 10 11 public void setClothing() { 12 this.clothing = ClothingFactory.getClothing(); 13 } 14 15 public void setType(String type) { 16 this.type = type; 17 } 18 19 public String getType() { 20 return this.type; 21 } 22 23 public abstract void dress(); 24 }
1 public abstract class Clothing { 2 3 public abstract void personDressCloth(Person person); 4 }
1 public class Lady extends Person { 2 3 public Lady() { 4 setType("女人"); 5 } 6 7 public void dress() { 8 Clothing clothing = getClothing(); 9 clothing.personDressCloth(this); 10 } 11 }
1 public abstract class Clothing { 2 3 public abstract void personDressCloth(Person person); 4 }
1 public class Jacket extends Clothing { 2 3 public void personDressCloth(Person person) { 4 System.out.println(person.getType() + "穿马甲"); 5 } 6 }
1 @SuppressWarnings("static-access") 2 public class ClothingFactory { 3 private static Clothing clothing; 4 5 public ClothingFactory(Clothing clothing){ 6 this.clothing = clothing; 7 } 8 9 public static Clothing getClothing() { 10 return clothing; 11 } 12 13 }
1 public class Trouser extends Clothing { 2 3 public void personDressCloth(Person person) { 4 System.out.println(person.getType() + "穿裤子"); 5 } 6 }
转载于:https://www.cnblogs.com/huzi007/p/4045500.html