欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

【四】Java设计模式GOF23之抽象工厂模式

程序员文章站 2024-01-20 19:45:04
...

目录

【四】Java设计模式GOF23之抽象工厂模式

CarFactory.java

public interface CarFactory {
	Engine createEngine();
	Seat createSeat();
	Tyre createTyre();
}

LowCarFactory.java

public class LowCarFactory implements CarFactory{

	@Override
	public Engine createEngine() {
		return new LowEngine();
		
	}

	@Override
	public Seat createSeat() {
		return new LowSeat();
		
	}

	@Override
	public Tyre createTyre() {
		return new LowTyre();
		
	}

}

LuxuryCarFactory.java

public class LuxuryCarFactory implements CarFactory{

	@Override
	public Engine createEngine() {
		return new LuxuryEngine();
		
	}

	@Override
	public Seat createSeat() {
		return new LuxurySeat();
		
	}

	@Override
	public Tyre createTyre() {
		return new LuxuryTyre();
		
	}

}

Engine.java

public interface Engine {
	void run();
	void start();
}

class LuxuryEngine implements Engine{

	@Override
	public void run() {
		System.out.println("ת�ÿ�");
		
	}

	@Override
	public void start() {
		System.out.println("�����죡�����Զ���ͣ��");
		
	}
	
}

class LowEngine implements Engine{

	@Override
	public void run() {
		System.out.println("ת����");
		
	}

	@Override
	public void start() {
		System.out.println("�������������Զ���ͣ��");
		
	}
	
}

Seat.java

public interface Seat {
	void massage();
}

class LuxurySeat implements Seat{

	@Override
	public void massage() {
		System.out.print("�����Զ���Ħ");
		
	}
	
}

class LowSeat implements Seat{

	@Override
	public void massage() {
		System.out.print("�����Զ���Ħ");
		
	}
	
}

Tyre.java

public interface Tyre {
	void revolve();
}

class LuxuryTyre implements Tyre{

	@Override
	public void revolve() {
		System.out.println("��ת��ĥ��");
		
	}
	
}

class LowTyre implements Tyre{

	@Override
	public void revolve() {
		System.out.println("��תĥ���");
		
	}
	
}

Client.java

public class Client {
	public static void main(String[] args) {
		CarFactory luxuryFactory = new LuxuryCarFactory();
		Engine luxuryEngine = luxuryFactory.createEngine();
		luxuryEngine.run();
		luxuryEngine.start();
		Seat luxurySeat = luxuryFactory.createSeat();
		Tyre luxuryTyre = luxuryFactory.createTyre();
	}
}