软件构造工厂模式

简单工厂模式

以代码作为主要例子

抽象产品

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();;
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值