工厂方法
优点:在产品维度扩展方便
想加产品-Bike,只需要Bike实现Moveable接口,然后重写go()
public class CarFactory {
public Moveable create() {
System.out.println("a car created!");
return new Car();
}
}
public interface Moveable {
void go();
}
public class Car implements Moveable {
public void go() {
System.out.println("Car go wuwuwuwuw....");
}
}
public class Broom implements Moveable{
@Override
public void go() {
System.out.println("broom flying chuachuachua .....");
}
}
public class Plane implements Moveable {
public void go() {
System.out.println("plane flying shushua....");
}
}
public class Main {
public static void main(String[] args) {
Moveable m = new CarFactory().create();
m.go();
}
}
抽象工厂
优点:在产品族维度扩展方便,在产品维度扩展麻烦。如下:如果再加一个产品族-火星工厂,只需要创建一个MarsFactory继承AbastractFactory,然后实现各个抽象方法就行了;但是如果在AbastractFactory中再加一个产品-Cloth,那么之前的所有工厂都需要加Cloth的实现。
public abstract class AbastractFactory {
abstract Food createFood();
abstract Vehicle createVehicle();
abstract Weapon createWeapon();
}
//魔法工厂
public class MagicFactory extends AbastractFactory {
@Override
Food createFood() {
return new MushRoom();
}
@Override
Vehicle createVehicle() {
return new Broom();
}
@Override
Weapon createWeapon() {
return new MagicStick();
}
}
//现代工厂
public class ModernFactory extends AbastractFactory {
@Override
Food createFood() {
return new Bread();
}
@Override
Vehicle createVehicle() {
return new Car();
}
@Override
Weapon createWeapon() {
return new AK47();
}
}
public abstract class Food {
abstract void printName();
}
public abstract class Vehicle { //interface
abstract void go();
}
public abstract class Weapon {
abstract void shoot();
}
public class Bread extends Food{
public void printName() {
System.out.println("wdm");
}
}
public class AK47 extends Weapon{
public void shoot() {
System.out.println("tututututu....");
}
}
public class Broom extends Vehicle{
public void go() {
System.out.println("Car go wuwuwuwuw....");
}
}
public class Car extends Vehicle{
public void go() {
System.out.println("Car go wuwuwuwuw....");
}
}
public class MagicStick extends Weapon{
public void shoot() {
System.out.println("diandian....");
}
}
public class MushRoom extends Food{
public void printName() {
System.out.println("dmg");
}
}
public class Main {
public static void main(String[] args) {
AbastractFactory f = new ModernFactory();
Vehicle c = f.createVehicle();
c.go();
Weapon w = f.createWeapon();
w.shoot();
Food b = f.createFood();
b.printName();
}
}