java设计模式(精通系列)-factory

工厂模式:利用工厂来创建相应的类
这里写图片描述

public class App {
    public static void main(String[] args) {
        WeaponFactory factory=WeaponFactory.factory(builder -> {
            builder.add(WeaponType.SWORD,Sword::new);
            builder.add(WeaponType.AXE,Axe::new);
            builder.add(WeaponType.SPEAR,Spear::new);
            builder.add(WeaponType.BOW,Bow::new);
        });
        Weapon axe=factory.create(WeaponType.AXE);
        System.out.println(axe.toString());


    }
}
public class Axe implements Weapon {
    @Override
    public String toString() {
        return "Axe";
    }
}
public class Bow implements Weapon {
    @Override
    public String toString() {
        return "Bow";
    }
}
public interface Builder {
    void add(WeaponType name, Supplier<Weapon> supplier);
}
public class Spear implements Weapon {
    @Override
    public String toString() {
        return "Spear";
    }
}
public class Sword implements Weapon {
    @Override
    public String toString() {
        return "Sword";
    }
}
public interface Weapon {
}
public interface WeaponFactory {
    Weapon create(WeaponType name);
    static WeaponFactory factory(Consumer<Builder> consumer){
        Map<WeaponType,Supplier<Weapon>> map=new HashMap<>();
        consumer.accept(map::put);
        return name->map.get(name).get();
    }
}
public enum  WeaponType {
    SWORD, AXE, BOW, SPEAR
}

代码解析:这里主要用到了java8的一些功能,如:Consumer and Supplier
可以参照我的博客http://blog.csdn.net/u011747152/article/details/78202994
这里参数传入到WeaponFactory

//        Consumer<Builder> consumer=builder -> {
//            builder.add(WeaponType.SWORD,Sword::new);
//            builder.add(WeaponType.AXE,Axe::new);
//            builder.add(WeaponType.SPEAR,Spear::new);
//            builder.add(WeaponType.BOW,Bow::new);
//        };
public interface WeaponFactory {
    Weapon create(WeaponType name);
    static WeaponFactory factory(Consumer<Builder> consumer){
        Map<WeaponType,Supplier<Weapon>> map=new HashMap<>();//构造一个空map
        consumer.accept(map::put);//这里调用map的put方法因为map刚好是参数传入的格式,所以就把参  数全存到map里了
        return name->map.get(name).get();//map.get(name)是一个Supplier<Weapon>
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值