1.面向接口编程
public interface IFruit {
void plant();
void harvest();
}
public class Grape implements IFruit{
public void plant(){
System.out.println("葡萄种植...");
}
public void harvest(){
System.out.println("葡萄收获...");
}
}
public class Strawberry implements IFruit{
public void plant(){
System.out.println("草莓种植...");
}
public void harvest(){
System.out.println("草莓收获...");
}
}
public class FruitGarden {
public static IFruit factory(String which){
IFruit iFruit = null;
if (which.equalsIgnoreCase("grape")){
iFruit = new Grape();
}
if (which.equalsIgnoreCase("strawberry")){
iFruit = new StrawBerry();
}
return iFruit;
}
}
public class Client1 {
public static void main(String[] args) {
String[] strings = {"grape","strawberry"};
for (String str : strings){
IFruit fruit = FruitGarden.factory(str);
fruit.plant();
fruit.harvest();
}
}
}
2.简单工厂模式实例
使用java反射改进:
public class FruitGarden {
public static IFruit factory(String which) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
IFruit iFruit = null;
String pn = FruitGarden.class.getPackage().getName();
StringBuilder sb = new StringBuilder();
sb.append(pn);
sb.append(".");
sb.append(Character.toUpperCase(which.charAt(0)));
sb.append(which.substring(1).toLowerCase());
iFruit = (IFruit)Class.forName(sb.toString()).newInstance();
return iFruit;
}
}
public class Client1 {
public static void main(String[] args) {
String[] strings = {"grape","strawberry"};
for (String str : strings){
IFruit fruit = null;
try {
fruit = FruitGarden.factory(str);
fruit.plant();
fruit.harvest();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
}
}
}
}
网友评论