An effective way to use pattern to instead of multiple if else statements
2011-07-19 15:14
573 查看
We often face many if-else statements during the development, that's a little boring.
We can use pattern to change this, such as Strategy, and Command patterns.
Here is an example for Command pattern:
We can use pattern to change this, such as Strategy, and Command patterns.
Here is an example for Command pattern:
package com.stefli.test.pattern.ifelse; public class IfElseTester { public enum Command { A { void exec() { p("A command executed!"); } }, B { void exec() { p("B command executed!"); } }, C { void exec() { p("C command executed!"); } }; abstract void exec(); } public static void p(String line) { System.out.println(line); } public static void main(String[] args) { if (args.length != 1) { p("Wrong arguments!please try again!"); } oldMethod(args); newMethod(args); } public static void oldMethod(String[] args) { if ("A".equalsIgnoreCase(args[0])) { p("A executed in old method!"); } else if ("B".equalsIgnoreCase(args[0])) { p("B executed in old method!"); } else if ("C".equalsIgnoreCase(args[0])) { p("C executed in old method!"); } } public static void newMethod(String[] args) { Command.valueOf(args[0]).exec(); } }
相关文章推荐
- Component template should contain exactly one root element. If you are using v-if on multiple elements, use v-else-if to chain them instead.
- Write an Efficient Method to Check if a Number is Multiple of 3(快速判断3的倍数)
- ToDoList-An effective and flexible way to keep on top of your tasks(ToDoList-管理任务的有效工具)
- Quota Project: An effective way to manage the usage of your Swift-based storage cloud
- Know When to Use an Active Object Instead of a Mutex
- No way to map to an envelop schema without use of orchiestration.
- Whats the best way to split an array in ruby into multiple smaller arrays of random size
- Effective C# Item 4: Use Conditional Attributes Instead of #if
- 干活来袭:Effective Concurrency: Know When to Use an Active Object Instead of a Mutex
- Write an Efficient Method to Check if a Number is Multiple of 3
- Ten Ways to Check if an Integer Is a Power Of Two in C
- How to use Fiddler and HTTP replay to have an offline copy of your site
- Given two strings s and t, write a function to determine if t is an anagram of s.
- (NOT CLEAR)Question 21: Which of the following statements provide a valid reason not to use RTTI for distributed (i.e. networked
- Broadcast a message to multiple instance of an application
- Item 4:Use Conditional Attributes Instead of #if
- Ten Ways to Check if an Integer Is a Power Of Two in C
- Mosquitoes as a Way to Fight Malaria Instead of Spreading It
- In which of the following does a C++ developer use the placement new syntax to make new allocate an
- [zz]How to use Fiddler and HTTP replay to have an offline copy of your site