简单工厂模式
以代码作为主要例子
抽象产品
public abstract class Vehicle{
/**
*交通工具的形状
*/
public abstract void shape();
}
具体产品
public class Car extends Vehicle{
@Override
public void shape(){
System.out.println("汽车长这样");
}
}
public class Plane extends Vehicle{
@Override
public void shape(){
System.out.println("飞机长这样");
}
}
工厂
public class factory{
public static Vehicle create(String type){
switch(type){
case "Car":
return new Car();
break;
case "Plane":
return new Plane();
break;
default:
break;
}
}
}
运用
public class client{
public static void main(String[] args){
Vehicle car = factory.create("Car");
car.shape();
Vehicle plane = factory.create("Plane");
plane.shape();
}
}
工厂方法模式
抽象工厂
public interface factory{
public Vehicle createVehicle();
}
具体工厂
public class Carfactory implements factory{
@Override
public Car createVehicle(){
return new Car();
}
}
public class Planefactory implements factory{
@Override
public Plane createVehicle(){
return new Plane();
}
}
抽象产品
public abstract class Vehicle{
/**
*交通工具的形状
*/
public abstract void shape();
}
具体产品
public class Car extends Vehicle{
@Override
public void shape(){
System.out.println("汽车长这样");
}
}
public class Plane extends Vehicle{
@Override
public void shape(){
System.out.println("飞机长这样");
}
}
运用
public class client{
public static void main(String[] args){
Carfactory carfactory = new Carfactory();
Car car = carfactory.createVehicle();
Planefactory planefactory = new Planefactory();
Plane plane = planefactory.createVehicle();
}
}
抽象工厂模式
工厂类
public interface myfactory{
public Car createCar();
public Plane createPlane();
}
public class Factory implements myfactory{
public Car createCar(){
return new Car();
}
public Plane createPlane(){
return new Plane();
}
}
产品类
public interface myCar{
public void shape();
}
public interface myPlane{
public void shape();
}
public class Car implements myCar{
public void shape(){
System.out.println("汽车长这样");
}
}
public class Plane implements myPlane{
public void shape(){
System.out.println("飞机长这样");
}
}
客户类
public class client{
public static void main(String[] args){
myfactory factory = new Factory();
factory.createCar().shape();;
factory.createPlane().shape();;
}
}