lundi 12 septembre 2016

Ignore if-else ladder and implements strategic design pattern

I am trying to implement strategic design pattern .

I have simple if-else ladder as below:

       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']);
        }

and i implemented strategic pattern upon it:

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
        };
    }
}

but i am confused as how to invoke a particular class based on condition

Like in above if-else ladder it checks for dataKeyinresponse value and then execute some statements

but here in strategic pattern how to see for the condition and then execute that class.

any help would be appreciated.

Aucun commentaire:

Enregistrer un commentaire