枚举与Lambda的结合

枚举与Lambda的结合 实现可读性良好的策略模式

枚举类:
1.枚举类很安全,不能被实例化对象,甚至用反射都无法创建对象;
2.可以使用name()和oridnal()方法来返回枚举对象的实例名称和序数(从0开始);
3.所有的枚举类都有静态方法:values可以获取当前枚举类中的所有实例;
4.所有的枚举类都有静态方法:valuesOf可以将String类型的字符串转换为枚举类型的对象;
5.枚举常量必须最先声明,并且常量之间需要用逗号隔开,最后一个常量用分号;
6.枚举常量之后若使用{},则表示当前枚举类的匿名内部类;
7.使用switch操作枚举。

策略模式:
1.定义一系列的算法,把它们一个个封装起来, 并且使它们可相互替换;
2.在有多种算法相似的情况下,使用 if…else 所带来的复杂和难以维护;
3.一个系统有许多许多类,而区分它们的只是他们直接的行为;
4.在策略模式中,我们创建表示各种策略的对象和一个行为随着策略对象改变而改变的 context 对象。

案例需求:
1.一个班级(SchoolClass)有名字(String)、有很多学生(List<Student>)、和语数外三个课代表(List<Representative>);
2.有了学生List<Student>、和课代表List<Representative>,需要生成班级(SchoolClass)实例,

解决方案:
使用枚举来找到具体的课代表并赋给班级(SchoolClass)实例

Main方法调用:LambdaEnum

public class LambdaEnum {
   
    private static List<Student> classOneStudents = new ArrayList<>();
    private static List<Representative> representatives = new ArrayList<>();

    static {
   
        classOneStudents.add(new Student("Weison",5,"男",90,2));
        classOneStudents.add(new Student("Evan",5,"女",60,1));
        classOneStudents.add(new Student("Jack",5,"男",90,3));
        classOneStudents.add(new Student("Luis",5,"男",60,3));
        classOneStudents.add(new Student("Elen",5,"女",90,5));
        classOneStudents.add(new Student("Obam",5,"男",70,1));
        classOneStudents.add(new Student("Bush",5,"女",90,1));
        ChineseRepresentative chineseRepresentative =
                new ChineseRepresentative("Evan", 6, "女", 80, 2);
        MathematicsRepresentative mathematicsRepresentative =
                new MathematicsRepresentative("Jack", 7, "男", 70, 2);
        EnglishRepresentative englishRepresentative =
                new EnglishRepresentative("Luis", 8, "女"
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值