Call methods depending on some setting?
I have some code which looks like this:
if(someCondition)
{
SomeClass1.DoSomething();
SomeClass2.DoSomethingElse();
SomeClass3.DoSomethingElseAgain();
}
if(someOtherCondition)
{
SomeClass4.WhatEv开发者_JAVA百科er();
}
Now, sometimes all of those methods should be called, sometimes only some. For example, sometimes I only want to call
SomeClass2.DoSomethingElse();
SomeClass3.DoSomethingElseAgain();
The rest should not be called. Is there a nice pattern or trick to achieve that?
Thanks :-)
The Strategy pattern would work nice in this situation: http://en.wikipedia.org/wiki/Strategy_pattern
Example:
class StrategyExample {
public static void main(String[] args) {
Context context;
context = new Context(new SomeCondition());
context.executeStrategy();
context = new Context(new SomeOtherCondition());
context.executeStrategy();
}
}
// The classes that implement a concrete strategy should implement this. The context class uses this to call the concrete strategy
interface Strategy {
void DoSomething();
}
// Implements the algorithm using the strategy interface
class SomeCondition implements Strategy {
public void DoSomething() {
// some condition code
}
}
// Implements the algorithm using the strategy interface
class SomeOtherCondition implements Strategy {
public void DoSomething() {
// dome other condition code
}
}
// Configured with a concrete strategy object
class Context {
private Strategy strategy;
// Constructor
public Context(Strategy strategy) {
this.strategy = strategy;
}
public void executeStrategy() {
strategy.DoSomething();
}
}
You could create a List<Action>
, and for each of the conditions (the if(someCondition)
part), add the method(s) you want to call to the Action list, and then at the end loop through the actions and execute each one.
If your methods do not match the Action<T>
pattern (zero or one parameter, does not return a value), you could create another custom delegate that would act in the same way.
And here is some pseudocode for you:
static void Main(string[] args)
{
List<Action> actionList = new List<Action>();
if (true)
{
actionList.Add(new Action(DoSomething));
}
// etc.
foreach (Action a in actionList)
{
a();
}
}
static void DoSomething()
{
// Code to do something.
}
I know this seems like a longer, more convoluted way of doing the if/else approach from the OP's post, but in some cases this could actually be a better design (just not all cases). It's hard to know what would work well, since the OP was so vague.
I think you can use switch case block as below,
switch (ext.ToLower()) { case ".htm": case ".html": type = "text/HTML"; break;
case ".txt":
type = "text/plain";
break;
case ".doc":
case ".rtf":
type = "Application/msword";
break;
case ".xls":
type = "application/vnd.ms-excel";
break;
case ".xlsx":
type = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
break;
}
精彩评论