1.目录结构
2.
Fruit接口,Apple 和 Banana都实现接口,FruitFactory接口,AppleFactory 和 BananaFactory实现接口。要是再加一个一个水果,也就只需再添加相应的工程即可
3.具体实现
Fruit,java
public interface Fruit {
public void get();
}
Apple.java
public class Apple implements Fruit{
@Override
public void get() {
// TODO Auto-generated method stub
System.out.println("得到苹果");
}
}
Banana.java
public class Banana implements Fruit{
@Override
public void get() {
// TODO Auto-generated method stub
System.out.println("得到香蕉");
}
}
FruitFactory.java
public interface FruitFactory {
public Fruit getFruit();
}
AppleFactory.java
public class AppleFactory implements FruitFactory{
@Override
public Fruit getFruit() {
// TODO Auto-generated method stub
return new Apple();
}
}
Banana.java
public class BananaFactory implements FruitFactory{
@Override
public Fruit getFruit() {
// TODO Auto-generated method stub
return new Banana();
}
}
Client.java
public class Client {
public static void main(String[] args) {
FruitFactory appleFactory = new AppleFactory();
Fruit apple = appleFactory.getFruit();
apple.get();
}
}