示例:
首先,我们定义一个接口来实现所有策略的行为:
public interface paymentstrategy { void pay(double amount);}
接下来,我们定义具体的策略类来实现不同的支付方式:
public class creditcardpaymentstrategy implements paymentstrategy { private string name; private string cardnumber; private string cvv; private string dateofexpiry; public creditcardpaymentstrategy(string name, string cardnumber, string cvv, string dateofexpiry) { this.name = name; this.cardnumber = cardnumber; this.cvv = cvv; this.dateofexpiry = dateofexpiry; } public void pay(double amount) { system.out.println(amount + " paid with credit card"); }} public class paypalpaymentstrategy implements paymentstrategy { private string emailid; private string password; public paypalpaymentstrategy(string emailid, string password) { this.emailid = emailid; this.password = password; } public void pay(double amount) { system.out.println(amount + " paid using paypal"); }} public class cashpaymentstrategy implements paymentstrategy { public void pay(double amount) { system.out.println(amount + " paid in cash"); }}
现在,我们可以在客户端代码中创建不同的策略对象,并将它们传递给一个统一的支付类中,这个支付类会根据传入的策略对象来调用相应的支付方法:
public class shoppingcart { private list<item> items; public shoppingcart() { this.items = new arraylist<>(); } public void additem(item item) { this.items.add(item); } public void removeitem(item item) { this.items.remove(item); } public double calculatetotal() { double sum = 0; for (item item : items) { sum += item.getprice(); } return sum; } public void pay(paymentstrategy paymentstrategy) { double amount = calculatetotal(); paymentstrategy.pay(amount); }}
现在我们可以使用上述代码来创建一个购物车,向其中添加一些商品,然后使用不同的策略来支付:
public class main { public static void main(string[] args) { shoppingcart cart = new shoppingcart(); item item1 = new item("1234", 10); item item2 = new item("5678", 40); cart.additem(item1); cart.additem(item2); // pay by credit card cart.pay(new creditcardpaymentstrategy("john doe", "1234567890123456", "786", "12/22")); // pay by paypal cart.pay(new paypalpaymentstrategy("myemail@example.com", "mypassword")); // pay in cash cart.pay(new cashpaymentstrategy()); //--------------------------或者提前将不同的策略对象放入map当中,如下 map<string, paymentstrategy> paymentstrategies = new hashmap<>(); paymentstrategies.put("creditcard", new creditcardpaymentstrategy("john doe", "1234567890123456", "786", "12/22")); paymentstrategies.put("paypal", new paypalpaymentstrategy("myemail@example.com", "mypassword")); paymentstrategies.put("cash", new cashpaymentstrategy()); string paymentmethod = "creditcard"; // 用户选择的支付方式 paymentstrategy paymentstrategy = paymentstrategies.get(paymentmethod); cart.pay(paymentstrategy); }}
工厂模式(factory pattern)将每个条件分支的实现作为一个独立的产品类,然后使用一个工厂类来创建具体的产品对象。这种方法可以将大量的if else语句转换为对象的创建过程,从而提高代码的可读性和可维护性。
示例:
// 定义一个接口public interface stringprocessor { public void processstring(string str);} // 实现接口的具体类public class lowercasestringprocessor implements stringprocessor { public void processstring(string str) { system.out.println(str.tolowercase()); }} public class uppercasestringprocessor implements stringprocessor { public void processstring(string str) { system.out.println(str.touppercase()); }} public class reversestringprocessor implements stringprocessor { public void processstring(string str) { stringbuilder sb = new stringbuilder(str); system.out.println(sb.reverse().tostring()); }} // 工厂类public class stringprocessorfactory { public static stringprocessor createstringprocessor(string type) { if (type.equals("lowercase")) { return new lowercasestringprocessor(); } else if (type.equals("uppercase")) { return new uppercasestringprocessor(); } else if (type.equals("reverse")) { return new reversestringprocessor(); } throw new illegalargumentexception("invalid type: " + type); }} // 测试代码public class main { public static void main(string[] args) { stringprocessor sp1 = stringprocessorfactory.createstringprocessor("lowercase"); sp1.processstring("hello world"); stringprocessor sp2 = stringprocessorfactory.createstringprocessor("uppercase"); sp2.processstring("hello world"); stringprocessor sp3 = stringprocessorfactory.createstringprocessor("reverse"); sp3.processstring("hello world"); }}
看起来还是有if...else,但这样的代码更加简洁易懂,后期也便于维护....
映射表(map)使用一个映射表来将条件分支的实现映射到对应的函数或方法上。这种方法可以减少代码中的if else语句,并且可以动态地更新映射表,从而提高代码的灵活性和可维护性。
示例:
import java.util.hashmap;import java.util.map;import java.util.function.function; public class mappingtableexample { private map<string, function<integer, integer>> functionmap; public mappingtableexample() { functionmap = new hashmap<>(); functionmap.put("add", x -> x + 1); functionmap.put("sub", x -> x - 1); functionmap.put("mul", x -> x * 2); functionmap.put("div", x -> x / 2); } public int calculate(string operation, int input) { if (functionmap.containskey(operation)) { return functionmap.get(operation).apply(input); } else { throw new illegalargumentexception("invalid operation: " + operation); } } public static void main(string[] args) { mappingtableexample example = new mappingtableexample(); system.out.println(example.calculate("add", 10)); system.out.println(example.calculate("sub", 10)); system.out.println(example.calculate("mul", 10)); system.out.println(example.calculate("div", 10)); system.out.println(example.calculate("mod", 10)); // 抛出异常 }}
数据驱动设计(data-driven design) 将条件分支的实现和输入数据一起存储在一个数据结构中,然后使用一个通用的函数或方法来处理这个数据结构。这种方法可以将大量的if else语句转换为数据结构的处理过程,从而提高代码的可扩展性和可维护性。
示例:
import java.util.arraylist;import java.util.list;import java.util.function.function; public class datadrivendesignexample { private list<function<integer, integer>> functionlist; public datadrivendesignexample() { functionlist = new arraylist<>(); functionlist.add(x -> x + 1); functionlist.add(x -> x - 1); functionlist.add(x -> x * 2); functionlist.add(x -> x / 2); } public int calculate(int operationindex, int input) { if (operationindex < 0 || operationindex >= functionlist.size()) { throw new illegalargumentexception("invalid operation index: " + operationindex); } return functionlist.get(operationindex).apply(input); } public static void main(string[] args) { datadrivendesignexample example = new datadrivendesignexample(); system.out.println(example.calculate(0, 10)); system.out.println(example.calculate(1, 10)); system.out.println(example.calculate(2, 10)); system.out.println(example.calculate(3, 10)); system.out.println(example.calculate(4, 10)); // 抛出异常 }}
以上就是java中如何优化大量if...else...的详细内容。
