->工廠方法模式
//抽象產(chǎn)品角色
public interface Moveable {
void run();
}
//具體產(chǎn)品角色
public class Plane implements Moveable {
@Override
public void run() {
System.out.println("plane....");
}
}
public class Broom implements Moveable {
@Override
public void run() {
System.out.println("broom.....");
}
}
//抽象工廠
public abstract class VehicleFactory {
abstract Moveable create();
}
//具體工廠
public class PlaneFactory extends VehicleFactory{
public Moveable create() {
return new Plane();
}
}
public class BroomFactory extends VehicleFactory{
public Moveable create() {
return new Broom();
}
}
//測(cè)試類public class Test {
public static void main(String[] args) {
VehicleFactory factory = new BroomFactory();
Moveable m = factory.create();
m.run();
}
}
->抽象工廠
//抽象工廠類
public abstract class AbstractFactory {
public abstract Vehicle createVehicle();
public abstract Weapon createWeapon();
public abstract Food createFood();
}
//具體工廠類丑蛤,其中Food,Vehicle耗啦,Weapon是抽象類,
public class DefaultFactory extends AbstractFactory{
@Override
public Food createFood() {
return new Apple();
}
@Override
public Vehicle createVehicle() {
return new Car();
}
@Override
public Weapon createWeapon() {
return new AK47();
}
}
//測(cè)試類
public class Test {
public static void main(String[] args) {
AbstractFactory f = new DefaultFactory();
Vehicle v = f.createVehicle();
v.run();
Weapon w = f.createWeapon();
w.shoot();
Food a = f.createFood();
a.printName();
}
}