工厂模式_面向抽象类编程

public abstract class AbstractFatory {

public abstract Vehicle createVehicle();

public abstract Weapon createWeapon();

public abstract food createFood();

}

public class DefaultFactory extends AbstractFatory{

@Override

public Vehicle createVehicle() {

return new Car();

}

@Override

public Weapon createWeapon() {

return new AK47();

}

@Override

public food createFood() {

return new Apple();

}

}

public class MagicFactory extends AbstractFatory{

@Override

public Vehicle createVehicle() {

return new Car();

}

@Override

public Weapon createWeapon() {

return new Gun();

}

@Override

public food createFood() {

return new Apple();

}

}

public class Apple extends food{

@Override

public void print() {

System.out.println("apple");

}

}

public class AK47 extends Weapon{

@Override

public void shoot(){

System.out.println("shoot.....");

}

}

public class Gun extends Weapon{
@Override
public void shoot() {
System.out.println("Gun...");
}
}
public abstract class Vehicle {
public abstract void run();
}
public abstract class Weapon {
public abstract void shoot();
}
public abstract class food {
public abstract void print();
}
public class Car extends Vehicle{
@Override
public void run(){
System.out.println("Car drive....");
}
}
public class Test {
public static void main(String[] args) {
AbstractFatory af=new DefaultFactory();
Car car=(Car)af.createVehicle();
car.run();
AK47 ak=(AK47)af.createWeapon();
ak.shoot();
Apple a=(Apple)af.createFood();
a.print();
}
}

你可能感兴趣的:(apple,编程)