java子弹问题if语句,Java:使用多态来避免if语句?

I'm attempting to write a java program that initializes certain layouts based on what the user selects. What I want to do is try to avoid writing a bunch of if-statements so the code can be scalable for future use if more layouts need to be added. I heard the best way to implement this is using polymorphism but my understanding of polymorphism is still a little fuzzy.

Say I want to implement this case:

if (user choose layoutA) { initialize layoutA }

if (user choose layoutB) { initialize layoutB }

if (user choose layoutC) {initialize layoutC }

I was thinking of creating an interface for classes to implement. What confuses me is how it works in main(), won't I still need a conditional if or switch statement to figure out which class to instantiate?

interface LayoutHandler {

public void initializeLayout();

}

class layoutA implements LayoutHandler {

public void initialize Layout {initialize layout A}

}

class layoutB implements LayoutHandler {

public void initialize Layout {initialize layout B}

}

class layoutC implements LayoutHandler {

public void initialize Layout {initialize layout C}

}

Then somewhere out in main:

public static void main() {

getlayoutselectionfromuser()

if (user choose layoutA) { LayoutHandler layout = new layoutA(); }

if (user choose layoutB) { LayoutHandler layout = new layoutB(); }

if (user choose layoutC) { LayoutHandler layout = new layoutC(); }

}

Wouldn't I still require a switch or if-statement in the main program to figure out which layout the user has chosen during runtime?

Thanks!

解决方案

Generally, it will be difficult to avoid some kind of conditional statement at some point to create an instance of the appropriate class.

The benefit of polymorphism comes when you have multiple if-else statements in multiple places. The polymorphism encapsulates the conditional logic for you. See this question for some other discussions on this topic.

This sort of scattered logic:

void initLayout() {

if (user choose layoutA) { initialize layoutA }

if (user choose layoutB) { initialize layoutB }

if (user choose layoutC) {initialize layoutC }

}

void refreshLayout() {

if (user choose layoutA) { refresh layoutA }

if (user choose layoutB) { refresh layoutB }

if (user choose layoutC) { refresh layoutC }

}

void cleanupLayout() {

if (user choose layoutA) { cleanup layoutA }

if (user choose layoutB) { cleanup layoutB }

if (user choose layoutC) { cleanup layoutC }

}

Gets replaced with something simpler:

layout = getLayout(user choice);

layout.initLayout();

layout.refreshLayout();

layout.cleanupLayout();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值