23种设计模式之工厂模式

来源:互联网 发布:春晚 知乎 编辑:程序博客网 时间:2024/05/23 01:23

1、简单工厂模式(Simple Factory)


产品

abstract class Gun {

}


public class Mp5 extends Gun{
public Mp5(){
System.out.println("制造--->Mp5");
}
}


public class M16 extends Gun{
public M16(){
System.out.println("制造--->M16");
}
}


工厂

public class Factory {
public Gun createGun(String type){
if("M16".equals(type)){
return new M16();
}else if ("Mp5".equals(type)) {
return new Mp5();
}
return null;
}
}


客户

public class Customer {
public static void main(String[] args) {
Factory factory = new Factory();
factory.createGun("M16");
factory.createGun("Mp5");
}
}


2、工厂方法模式(Factory Method)

产品同上

工厂

public interface Factory {
Gun createGun();
}


public class FactoryM16 implements Factory{

@Override
public M16 createGun() {
return new M16();
}
}


public class FactoryMp5 implements Factory{

@Override
public Mp5 createGun() {
return new Mp5();
}
}


客户

public class Customer {
public static void main(String[] args) {
FactoryMp5 factoryMp5 = new FactoryMp5();
Mp5 mp5 = factoryMp5.createGun();

FactoryM16 factoryM16 = new FactoryM16();
M16 m16 = factoryM16.createGun();
}
}


3、抽象工厂模式(Abstract Factory)

产品

public interface ISightA {
public void show();
}


public interface ISightB {
public void show();
}


public class SightA implements ISightA{
@Override
public void show() {
System.out.println("这是A型瞄准镜");
}
}


public class SightB implements ISightB{
@Override
public void show() {
System.out.println("这是B型瞄准镜");
}
}


工厂

public interface IFactory {
public ISightA createSightA();
public ISightB createSightB();
}


public class Factory implements IFactory{


@Override
public ISightA createSightA() {
return new SightA();
}


@Override
public ISightB createSightB() {
return new SightB();
}
}


客户

public class Customer {
public static void main(String[] args) {
IFactory factory = new Factory();
factory.createSightA().show();
factory.createSightB().show();
}
}

原创粉丝点击