close
Abstract Factory Pattern相對於Simple Factory Pattern只是將不同的Factory抽象化後,而多了Abstract Factory這一層。
Manner.java
public interface Manner {
public void eatSomething() ;
}
Person.java
public class Person implements Manner {
public void eatSomething() {
System.out.println("Person eat something");
}
}
Dog.java
public class Dog implements Manner {
public void eatSomething() {
System.out.println("Dog eat something");
}
}
Cat.java
public class Cat implements Manner {
public void eatSomething() {
System.out.println("Cat eat something");
}
}
Exercise.java
interface Exercise {
public void getPlay() ;
}
Adult.java
public class Adult implements Exercise {
@Override
public void getPlay() {
System.out.println("Adult play badminton");
}
}
Child.java
public class Child implements Exercise {
@Override
public void getPlay() {
System.out.println("child play basketball");
}
}
AbstractFactory.java
abstract class AbstractFactory {
public abstract Manner getEat(String type) ;
public abstract Exercise getPlay(String sport) ;
}
ExerciseFactory.java
public class ExerciseFactory extends AbstractFactory {
public Exercise getPlay(String sport){
if(sport.equals("Child")){
return new Child() ;
}else if(sport.equals("Adult")){
return new Adult() ;
}
return null ;
}
@Override
public Manner getEat(String type) {
return null;
}
}
MannerFactory.java
public class MannerFactory extends AbstractFactory {
public Manner getEat(String type){
if(type.equals("Person")){
return new Person() ;
}else if(type.equals("Dog")){
return new Dog() ;
}else if(type.equals("Cat")){
return new Cat() ;
}
return null ;
}
@Override
public Exercise getPlay(String sport) {
return null;
}
}
FactoryProducer.java
public class FactoryProducer {
public static AbstractFactory getFactory(String choice){
if(choice.equals("Exercise")){
return new ExerciseFactory() ;
}else if(choice.equals("Manner")){
return new MannerFactory() ;
}
return null ;
}
}
Main.java
public class Main {
public static void main(String[] args) {
FactoryProducer factoryProducer=new FactoryProducer() ;
factoryProducer.getFactory("Manner").getEat("Person").eatSomething();
factoryProducer.getFactory("Manner").getEat("Dog").eatSomething();
factoryProducer.getFactory("Manner").getEat("Cat").eatSomething();
FactoryProducer factoryProducer1=new FactoryProducer() ;
factoryProducer1.getFactory("Exercise").getPlay("Adult").getPlay();
factoryProducer1.getFactory("Exercise").getPlay("Child").getPlay();
}
}
全站熱搜
留言列表
