Programmer Log10[JAVASE新特性总结]_19.10.28

1.枚举

1.1 多例设计模式

首先回顾一下多例设计模式:构造方法私有化,在类内部提供若干个实例化对象,后面通过static方法返回。目的是限制本类实例化对象的产生个数

class Color { private String title ; public static final int RED_FLAG = 1 ; public static final int GREEN_FLAG = 2 ; public static final int BLUE_FLAG = 3 ; private static final Color RED = new Color("RED") ; private static final Color GREEN = new Color("GREEN") ; private static final Color BLUE = new Color("BLUE") ; private Color(String title) { this.title = title ; } public static Color getInstance(int ch){ switch (ch) { case RED_FLAG : return RED ; case GREEN_FLAG : return GREEN ; case BLUE_FLAG : return BLUE ; default: return null ; } }@Override public String toString() { return this.title ; } } public class TestDemo { public static void main(String[] args) { System.out.println(Color.getInstance(Color.BLUE_FLAG)); } }

1.2 基于枚举的开发

enum Color{ RED,GREEN,BLUE } public class TestDemo{ public static void main(String[] args){ System.out.println(Color.BLUE); } }

1.3 Enum类

构造方法:

protected Enum(String name,int ordinal)

取得枚举名字:

public final String name()

取得枚举序号:

public final int ordinal()

取得所有枚举数据用values()

enum Color{ RED,GREEN,BLUE } public class TestDemo{ public static void main(String[] args){ for(Color temp:Color.values()){ System.out.println(temp.ordinal()+"="+temp.name()); } } }

1.4 定义结构

枚举中可以定义属性、方法、实现接口。

enum Color { RED("红⾊"),GREEN("绿⾊"),BLUE("蓝⾊") ; private String title; private Color(String title) { // 构造⽅法私有化 this.title = title; } @Override public String toString() { return this.title; } } public class TestDemo { public static void main(String[] args) { System.out.println(Color.BLUE); } }

2.接口定义加强

从JDK1.8开始可以使用default来定义普通方法,也可以使用static来定义静态方法

3.Lambda表达式

语法:(参数)—>单行语句; (参数)—>{多行语句};

函数式编程:

interface IMessage { public void print() ; // 这是⼀个接⼝,接⼝中的抽象⽅法必须由⼦类覆写。 } public class TestDemo { public static void main(String[] args) { // 函数式编程的使⽤,⽬的还是输出⼀句话 IMessage message = () -> System.out.println("Hello World"); message.print(); } }

使用函数式编程有一个前提:接口必须只有一个抽象方法

@FunctionalInterface 这个注解标明是一个函数式编程接口,只允许一个抽象方法

有参数和返回值时的写法:

@FunctionalInterface interface IMath { public int add(int x,int y) ; } public class TestDemo { public static void main(String[] args) { // 函数式编程的使⽤,⽬的还是输出⼀句话 IMath imath = (p1,p2)->p1+p2; System.out.println(imath.add(10,20)); } }

4.几种函数式接口

  1. 功能型函数式接⼝:public interface Function<T, R> R apply(T t);

  2. 供给型函数式接⼝: public interface Supplier T get();

  3. 消费型函数式接⼝:public interface Consumer void accept(T t);

  4. 断⾔型接⼝:public interface Predicate boolean test(T t);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值