您的位置:首页 > 其它

工厂设计模式

2017-10-12 19:56 169 查看

介绍

用工厂类的方法代替new,自主实例化对象

实现创建和调用的分离

简单工厂

public interface Moveable {
public void run();
}


public class Car implements Moveable {
@Override
public void run() {
System.out.println("car is running");
}
}


public class Train implements Moveable {
@Override
public void run() {
System.out.println("train is running");
}
}


public class MoveableFactory {

public static Moveable createMoveable(String moveable){
if(moveable=="car"){
return new Car();
}else if(moveable=="train"){
return new Train();
}
return null;
}
}


public class MyLearn {
public static void main(String[] args) throws Exception {
Moveable moveable = MoveableFactory.createMoveable("train");
moveable.run();  //train is running
}
}


开闭原则(OCP):对扩展开放,对修改关闭,即通过创建新的类来扩展,不应在原有代码上改动

简单工厂不满足开闭原则,如果增加新的Moveable,需要修改MoveableFactory类的代码,解决方法:工厂方法设计模式

工厂方法

public interface MoveableFactory {
public  Moveable createMoveable();
}


public class CarFactory implements MoveableFactory {
@Override
public  Moveable createMoveable() {
return new Car();
}
}


public class TrainFactory implements MoveableFactory {
@Override
public Moveable createMoveable() {
return new Train();
}
}


public static void main(String[] args) throws Exception {
Moveable moveable = new CarFactory().createMoveable();
moveable.run();  //car is running
}


每次增加一个产品都需要增加一个工厂,造成工厂泛滥

可以用反射解决这个问题

public class MoveableFactory {

public static Moveable createMoveable(Class<? extends Moveable> clazz) {
Object object=null;
try {
object = Class.forName(clazz.getName()).newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return (Moveable) object;
}

}


public static void main(String[] args) throws Exception {
Moveable moveable = MoveableFactory.createMoveable(Train.class);
moveable.run();
}


抽象工厂

创建一套产品族,例如QQ 换肤,一换一整套

public interface AbstractFactory {
public Shape createShape();
public Color createColor();
}


public class AppearanceOne implements AbstractFactory {

@Override
public Shape createShape() {
return new circle();
}

@Override
public Color createColor() {
return new Red();
}

}


public static void main(String[] args) throws Exception {
AbstractFactory f=new AppearanceOne();
Color color = f.createColor();
color.getColor();
Shape shape = f.createShape();
shape.getShape();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  设计模式