1,工厂方法模式(每个具体角色由其具体工厂产生),
①,抽象角色
②,具体角色
③,抽象工厂
④,具体工厂
抽象工厂模式(与工厂模式区别在于创建对象的复杂程度上)
①,抽象角色:
package method.factory;
public interface AbstractMove {
public void run();
}
②,具体角色
package method.factory;
public class Bus implements AbstractMove {
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println("This is a Bus running");
}
}
package method.factory;
public class Plan implements AbstractMove {
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println("This is Plan running");
}
}
③,抽象工厂
package method.factory;
public abstract class AbstractFactory {
abstract AbstractMove create();
}
④,具体工厂
package
method.factory;
public class BusFactory extends AbstractFactory {
@Override
AbstractMove create() {
// TODO Auto-generated method stub
return new Bus();
}
}
package
method.factory;
public class PlanFactory extends AbstractFactory {
@Override
AbstractMove create() {
// TODO Auto-generated method stub
return new Plan();
}
}
Test:
package
method.factory;
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
AbstractFactory af = new PlanFactory();
AbstractMove move = af.create();
move.run();
AbstractFactory af1 = new BusFactory();
AbstractMove move1 = af1.create();
move1.run();
}
}
result:
This
is Plan running
This is a Bus running