1.工厂方法模式
public interface Car {
void run();
}
public class BydCar implements Car{
@Override
public void run() {
System.out.println("我是比亚迪汽车");
}
}
public class AudoCar implements Car {
@Override
public void run() {
System.out.println("我是奥迪汽车");
}
}
public interface CarFactory {
Car createCar();
}
public class BydFactory implements CarFactory {
@Override
public Car createCar() {
return new BydCar();
}
}
public class AudoFactory implements CarFactory {
@Override
public Car createCar() {
return new AudoCar();
}
}
public class Client {
public static void main(String[] args) {
CarFactory factory1=new BydFactory();
CarFactory factory2=new AudoFactory();
Car car1 = factory1.createCar();
Car car2 = factory2.createCar();
car1.run();
car2.run();
}
}
2.抽象工厂模式
public interface CarFactory{
Seat createSeat();
Tyre createTyre();
}
class HighFactory implements CarFactory{
@Override
public Seat createSeat() {
return new HighSeat();
}
@Override
public Tyre createTyre() {
return new HighTyre();
}
}
class LowFactory implements CarFactory{
@Override
public Seat createSeat() {
return new LowSeat();
}
@Override
public Tyre createTyre() {
return new LowTyre();
}
}
interface Seat{
void sit();
}
interface Tyre{
void run();
}
class HighSeat implements Seat{
@Override
public void sit() {
System.out.println("高级座椅");
}
}
class LowSeat implements Seat{
@Override
public void sit() {
System.out.println("低级座椅");
}
}
class HighTyre implements Tyre{
@Override
public void run() {
System.out.println("高级轮胎");
}
}
class LowTyre implements Tyre{
@Override
public void run() {
System.out.println("低级轮胎");
}
}
public class Client {
public static void main(String[] args) {
CarFactory factory=new HighFactory();
Seat seat1 = factory.createSeat();
seat1.sit();
CarFactory factory2=new LowFactory();
Seat seat2 = factory2.createSeat();
seat2.sit();
}
}