目录
将每个条件分支的实现作为一个独立的策略类,然后使用一个上下文对象来选择要执行的策略。这种方法可以将大量的if else语句转换为对象之间的交互,从而提高代码的可维护性和可扩展性。
示例:
首先,我们定义一个接口来实现所有策略的行为:
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);
}
}
将每个条件分支的实现作为一个独立的产品类,然后使用一个工厂类来创建具体的产品对象。这种方法可以将大量的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,但这样的代码更加简洁易懂,后期也便于维护....
使用一个映射表来将条件分支的实现映射到对应的函数或方法上。这种方法可以减少代码中的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)); // 抛出异常
}
}
将条件分支的实现和输入数据一起存储在一个数据结构中,然后使用一个通用的函数或方法来处理这个数据结构。这种方法可以将大量的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)); // 抛出异常
}
}
👍点赞,你的认可是我创作的动力 !
🌟收藏,你的青睐是我努力的方向!
✏️评论,你的意见是我进步的财富!
我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div
总的来说,我对ruby还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用
关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。
给定这段代码defcreate@upgrades=User.update_all(["role=?","upgraded"],:id=>params[:upgrade])redirect_toadmin_upgrades_path,:notice=>"Successfullyupgradeduser."end我如何在该操作中实际验证它们是否已保存或未重定向到适当的页面和消息? 最佳答案 在Rails3中,update_all不返回任何有意义的信息,除了已更新的记录数(这可能取决于您的DBMS是否返回该信息)。http://ar.ru
我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t
我正在寻找执行以下操作的正确语法(在Perl、Shell或Ruby中):#variabletoaccessthedatalinesappendedasafileEND_OF_SCRIPT_MARKERrawdatastartshereanditcontinues. 最佳答案 Perl用__DATA__做这个:#!/usr/bin/perlusestrict;usewarnings;while(){print;}__DATA__Texttoprintgoeshere 关于ruby-如何将脚
Rackup通过Rack的默认处理程序成功运行任何Rack应用程序。例如:classRackAppdefcall(environment)['200',{'Content-Type'=>'text/html'},["Helloworld"]]endendrunRackApp.new但是当最后一行更改为使用Rack的内置CGI处理程序时,rackup给出“NoMethodErrorat/undefinedmethod`call'fornil:NilClass”:Rack::Handler::CGI.runRackApp.newRack的其他内置处理程序也提出了同样的反对意见。例如Rack
在选择我想要运行操作的频率时,唯一的选项是“每天”、“每小时”和“每10分钟”。谢谢!我想为我的Rails3.1应用程序运行调度程序。 最佳答案 这不是一个优雅的解决方案,但您可以安排它每天运行,并在实际开始工作之前检查日期是否为当月的第一天。 关于ruby-如何每月在Heroku运行一次Scheduler插件?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/8692687/
我有一个对象has_many应呈现为xml的子对象。这不是问题。我的问题是我创建了一个Hash包含此数据,就像解析器需要它一样。但是rails自动将整个文件包含在.........我需要摆脱type="array"和我该如何处理?我没有在文档中找到任何内容。 最佳答案 我遇到了同样的问题;这是我的XML:我在用这个:entries.to_xml将散列数据转换为XML,但这会将条目的数据包装到中所以我修改了:entries.to_xml(root:"Contacts")但这仍然将转换后的XML包装在“联系人”中,将我的XML代码修改为
我有一大串格式化数据(例如JSON),我想使用Psychinruby同时保留格式转储到YAML。基本上,我希望JSON使用literalstyle出现在YAML中:---json:|{"page":1,"results":["item","another"],"total_pages":0}但是,当我使用YAML.dump时,它不使用文字样式。我得到这样的东西:---json:!"{\n\"page\":1,\n\"results\":[\n\"item\",\"another\"\n],\n\"total_pages\":0\n}\n"我如何告诉Psych以想要的样式转储标量?解