简单工厂模式:
建立一个工厂类,对实现了同一接口的不同类进行实例的创建。
简单工厂的实质为:由一个工厂类根据传入的参数,动态的决定应该创建哪个产品类的示例
public interface Animal {
public void say();
}
public class Cat implements Animal{
@Override
public void say() {
System.out.println("喵···");
}
}
public class Dog implements Animal {
@Override
public void say() {
System.out.println("汪汪");
}
}
public class SampleFactory {
public static Animal getAnimal(Class c){
Animal animal = null;
try {
animal = (Animal) Class.forName(c.getName()).newInstance();
}catch (Exception e){
System.out.println("异常处理。。。");
}
return animal;
}
}
public class Client {
public static void main(String[] args) {
Animal cat = SampleFactory.getAnimal(Cat.class);
cat.say();
Animal dog = SampleFactory.getAnimal(Dog.class);
dog.say();
}
}
运行结果
工厂方法模式:
工厂父类(接口)负责定义产品对象的公共接口,子类工厂负责创建具体的产品对象
public interface Car {
void run();
}
public class Bike implements Car{
@Override
public void run() {
System.out.println("我是自行车");
}
}
public class Bus implements Car{
@Override
public void run() {
System.out.println("我是公交车");
}
}
public interface IFactory {
Car getCar();
}
public class BikeFactory implements IFactory {
@Override
public Car getCar() {
return new Bike();
}
}
public class BusFactory implements IFactory{
@Override
public Car getCar() {
return new Bus();
}
}
public class Client {
public static void main(String[] args) {
IFactory factory = null;
factory = new BikeFactory();
Car bike = factory.getCar();
bike.run();
factory = new BusFactory();
Car bus = factory.getCar();
bus.run();
}
}
运行结果
抽象工厂模式:
抽象工厂模式是工厂方法的升级版,用来创建一组相关或互相依赖的对象。
举个例子:高配汽车使用A类引擎和A类空调,低配汽车使用B类引擎和B类空调,此时需要两类工厂进行生产
public interface AirCondition {
}
public class AirConditionA implements AirCondition {
public AirConditionA(){
System.out.println("制造-->空调A");
}
}
public class AirConditionB implements AirCondition {
public AirConditionB(){
System.out.println("制造-->空调B");
}
}
public interface Engine {
}
public class EngineA implements Engine {
public EngineA(){
System.out.println("制造-->引擎A");
}
}
public class EngineB implements Engine{
public EngineB(){
System.out.println("制造-->引擎B");
}
}
public interface IFactory {
//制造发动机
public Engine createEngine();
//制造空调
public AirCondition createAirCondition();
}
public class FactoryA implements IFactory {
@Override
public Engine createEngine() {
return new EngineA();
}
@Override
public AirCondition createAirCondition() {
return new AirConditionA();
}
}
public class FactoryB implements IFactory{
@Override
public Engine createEngine() {
return new EngineB();
}
@Override
public AirCondition createAirCondition() {
return new AirConditionB();
}
}
public class Client {
public static void main(String[] args) {
FactoryA factoryA = new FactoryA();
factoryA.createEngine();
factoryA.createAirCondition();
FactoryB factoryB = new FactoryB();
factoryB.createEngine();
factoryB.createAirCondition();
}
}