简单工厂
public class EasyFactory {
graph getGraph(String str){
if (str==null)
return null;
if (str.equalsIgnoreCase("circle"))
return new Circle();
if (str.equalsIgnoreCase("square"))
return new Square();
return null;
}
}
interface graph{
void draw();
}
class Circle implements graph{
@Override
public void draw(){
System.out.println("Circle");
}
}
class Square implements graph{
@Override
public void draw() {
System.out.println("Square");
}
}
优点: 1、一个调用者想创建一个对象,只要知道其名称就可以了。 2、扩展性高,如果想增加一个产品,只要扩展一个工厂类就可以。 3、屏蔽产品的具体实现,调用者只关心产品的接口。
缺点:每次增加一个产品时,都需要增加一个具体类和对象实现工厂,使得系统中类的个数成倍增加,在一定程度上增加了系统的复杂度,同时也增加了系统具体类的依赖。这并不是什么好事。
抽象工厂模式
public class AbstractFactory{
public static void main(String[] args) {
factory1 cf=Facproduce.getfac("color");
factory1 cf1=Facproduce.getfac("graph1");
graph1 g1=cf1.getgraph("circle");
color c1=cf.getcolor("red");
g1.draw();
c1.fill();
}
}
class Facproduce{
public static factory1 getfac(String choice){
if (choice.equalsIgnoreCase("color"))
return new colorFact();
if (choice.equalsIgnoreCase("graph1"))
return new graphFac();
return null;
}
}
class colorFact extends factory1{
@Override
public color getcolor(String color) {
if (color.equalsIgnoreCase("red"))
return new Red();
if (color.equalsIgnoreCase("yellow"))
return new yellow();
return null;
}
@Override
public graph1 getgraph(String graph) {
return null;
}
}
class graphFac extends factory1{
@Override
public color getcolor(String color) {
return null;
}
@Override
public graph1 getgraph(String graph) {
if (graph.equalsIgnoreCase("circle"))
return new Circle1();
if (graph.equalsIgnoreCase("square"))
return new Square1();
return null;
}
}
abstract class factory1{
public abstract color getcolor(String color);
public abstract graph1 getgraph(String graph);
}
interface graph1{
void draw();
}
interface color{
void fill();
}
class Red implements color{
@Override
public void fill() {
System.out.println("red");
}
}
class yellow implements color{
@Override
public void fill() {
System.out.println("yellow");
}
}
class Circle1 implements graph1{
@Override
public void draw(){
System.out.println("Circle");
}
}
class Square1 implements graph1{
@Override
public void draw() {
System.out.println("Square");
}
}