java this 代替,有人可以推荐Java 8模式来代替switch语句吗?

I have following code:

public class A {

private String type;

String getType() { return type;}

}

Now in many code places I have code like this

switch (a.geType()) {

case "A" : return new Bla();

case "B" : return new Cop();

}

or somewhere else

switch (a.geType()) {

case "A" : return new Coda();

case "B" : return new Man();

}

(Note that I know I should use an Enumeration in production code).

What I want to achive is that when a new type is added to class A the compiler should flag all the switch statements that need to be adjusted?

Is there a java idiomatic way to do this?

解决方案

when a new type is added to class A the compiler should flag all the switch statements that need to be adjusted?

A good approach to this would be replacing switch statements with a more robust implementation of multiple dispatch, such as the Visitor Pattern:

interface VisitorOfA {

Object visitA(A a);

Object visitB(B b);

}

class A {

Object accept(VisitorOfA visitor) {

return visitor.visitA(this);

}

}

class B extends A {

Object accept(VisitorOfA visitor) {

return visitor.visitB(this);

}

}

With this infrastructure in place, you can remove your switch statements, replacing them with implementations of the visitor:

Object res = a.accept(new VisitorOfA() {

public Object visitA(A a) { return new Bla(); }

public Object visitB(B b) { return new Cop(); }

});

When you add a new subtype to A, say, class C, all you need to do is adding a new method to VisitorOfA:

Object visitC(C c);

Now the compiler will spot all places where this new method has not been implemented, helping you avoid problems at runtime.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值