抽象工厂模式
1.创建接口对象
public interface Tree {
void flower();
}
public interface Color {
void fill();
}
2.抽象工厂类
/**
* 抽象工厂类
*/
public abstract class AbstractFactory {
public abstract Color getColor(String color);
public abstract Tree getTree(String tree);
}
3.接口实现类
public class AppleTree implements Tree {
public void flower() {
System.out.println("Apple Tree flower");
}
}
public class RedColor implements Color {
public void fill() {
System.out.println("color red");
}
}
4.抽象接口实现类
public class TreeAbsFactory extends AbstractFactory {
public Color getColor(String color) {
return null;
}
public Tree getTree(String treeType) {
if (treeType == null){
return null;
}
if (treeType.equalsIgnoreCase("appletree")){
return new AppleTree();
} else if(treeType.equalsIgnoreCase("peertree")) {
return new PeerTree();
}
return null;
}
}
public class ColorAbsFactory extends AbstractFactory {
public Color getColor(String color) {
if (color == null){
return null;
}
if (color.equalsIgnoreCase("red")){
return new RedColor();
} else if(color.equalsIgnoreCase("yellow")){
return new YelloColor();
}
return null;
}
public Tree getTree(String tree) {
return null;
}
}
5.工厂实现类
public class FactoryProducer {
public static AbstractFactory getType(String type){
if (type.equalsIgnoreCase("tree")){
System.out.println("===========================");
return new TreeAbsFactory();
} else if(type.equalsIgnoreCase("color")){
return new ColorAbsFactory();
}
return null;
}
}