public interface People { public void eat(); public void run(); public void wear(); }
public class Xiaoming implements People{ @Override public void eat() { System.out.println("小明吃饭"); } @Override public void run() { System.out.println("小明跑步"); } @Override public void wear() { System.out.println("小明穿衣"); } } public class Xiaohong implements People{ @Override public void eat() { System.out.println("小红吃饭"); } @Override public void run() { System.out.println("小红跑步"); } @Override public void wear() { System.out.println("小红穿衣"); } }
public class PeopleFactory { public People getPeople(String name){ if(name.equals("Xiaoming")){ return new Xiaoming(); }else if(name.equals("Xiaohong")){ return new Xiaohong(); } return null; } }
public class StrategySign { private People people; public StrategySign(People people){ this.people = people; } public StrategySign(String name){ if(name.equals("Xiaoming")){ this.people = new Xiaoming(); }else if(name.equals("Xiaohong")){ this.people = new Xiaohong(); } } public void run(){ people.run(); } }
@Test public void testSign(){ PeopleFactory peopleFactory = new PeopleFactory(); People people = peopleFactory.getPeople("Xiaohong"); System.out.print("工厂模式-------------"); people.run(); StrategySign strategySign = new StrategySign("Xiaohong"); System.out.print("策略模式-------------");strategySign.run(); }
public class StrategySign { private People people; public StrategySign(People people){ this.people = people; } public StrategySign(String name){ if(name.equals("Xiaoming")){ this.people = new Xiaoming(); }else if(name.equals("Xiaohong")){ this.people = new Xiaohong(); } } public void run() { people.eat(); people.run(); people.eat(); } } @Test public void testSign(){ PeopleFactory peopleFactory = new PeopleFactory(); People people = peopleFactory.getPeople("Xiaohong"); System.out.print("工厂模式-------------"); people.eat(); System.out.print("工厂模式-------------"); people.run(); System.out.print("工厂模式-------------"); people.eat(); StrategySign strategySign = new StrategySign("Xiaohong"); System.out.print("策略模式-------------");strategySign.run(); }