我正在尝试实施战略设计模式。
我有简单的if-else阶梯,如下所示:
if(dataKeyinresponse === 'year') {
bsd = new Date(moment(new Date(item['key'])).startOf('year').format('YYYY-MM-DD'))
nestedbed = new Date(moment(new Date(item['key'])).endOf('year').format('YYYY-MM-DD'));
} else if(dataKeyinresponse === 'quarter') {
let tempDate = new Date(moment(new Date(item['key'])).add(2, 'months').format('YYYY-MM-DD'));
// nestedbed = new Date(moment(new Date(item['key'])).add(3, 'months').format('YYYY-MM-DD'));
nestedbed = new Date(moment(tempDate).endOf('month').format('YYYY-MM-DD'));
} else if(dataKeyinresponse === 'month') {
nestedbed = new Date(moment(new Date(item['key'])).endOf('month').format('YYYY-MM-DD'));
} else if(dataKeyinresponse === 'week') {
//Relying more on the ES start date for week
nestedbed = new Date(moment(new Date(item['key'])).weekday(7).format('YYYY-MM-DD'));
} else {
// bed = bucketStartDate;
nestedbed = new Date(item['key']);
}
我实施了战略模式:
interface emptyBucketInterface {
fnGetEmptyBuckets();
}
class year implements emptyBucketInterface {
fnGetEmptyBuckets() {
bsd = new Date(moment(new Date(item['key'])).startOf('year').format('YYYY-MM-DD'))
nestedbed = new Date(moment(new Date(item['key'])).endOf('year').format('YYYY-MM-DD'));
return {
"bsd": bsd,
"nestedbed": nestedbed
};
}
}
class quarter implements emptyBucketInterface {
fnGetEmptyBuckets() {
let tempDate = new Date(moment(new Date(item['key'])).add(2, 'months').format('YYYY-MM-DD'));
nestedbed = new Date(moment(tempDate).endOf('month').format('YYYY-MM-DD'));
return {
"tempDate": tempDate,
"nestedbed": nestedbed
};
}
}
class month implements emptyBucketInterface {
fnGetEmptyBuckets() {
nestedbed = new Date(moment(new Date(item['key'])).endOf('month').format('YYYY-MM-DD'));
return {
"nestedbed": nestedbed
};
}
}
class week implements emptyBucketInterface {
fnGetEmptyBuckets() {
nestedbed = new Date(moment(new Date(item['key'])).weekday(7).format('YYYY-MM-DD'));
return {
"nestedbed": nestedbed
};
}
}
但我很困惑如何根据条件
调用特定的类与上面的if-else梯形图一样,它会检查dataKeyinresponse
值,然后执行一些语句
但是在战略模式中如何查看条件然后执行该类。
任何帮助将不胜感激。
答案 0 :(得分:1)
策略模式的一个简单示例:
public class SomeClass {
private final Map<String, EmptyBucketInterface> strategies = new HashMap<String, EmptyBucketInterface>();
public SomeClass() {
strategies.put("year", new Year());
strategies.put("quarter", new Quarter());
strategies.put("month", new Month());
strategies.put("week", new Week());
}
public void doAction(String action) {
strategies.get(action).fnGetEmptyBuckets();
}
}
您可以看一下:https://www.tomasmalmsten.com/2011/01/create-factory-strategies-ifs/将策略创建封装在工厂中。
建议:您应该使用大写的第一个字母emptyBucketInterface
=&gt;命名您的课程。 EmptyBucketInterface