Hi I'm trying to move away from procedural programming and at the same time have a better appreciation for design patterns. I would like to know what Design Pattern can best represent the code below. It's an if else statement that basically outputs a value based on the time of day. This is just a sample of several if/else if statement I have in the code. Which OOP Pattern is appropriate (Iterator, Singleton, Factory.. )?
if($dayval == "Sun" && $date >= 0 && $date < 18) {
$timemax = 18;
$timeleft = ($timemax - $date);
if($timeleft == 开发者_运维知识库1) {
$arr = array('tstatus' => 'Trading begins today at 6:00pm (less than '. $timeleft. ' hour to go) - have a great trade week!',
'tcode' => 'closed');
}
else {
$arr = array('tstatus' => 'Trading begins today at 6:00pm (less than ' .$timeleft. ' hours to go) - have a great trade week!',
'tcode' => 'closed'
);
}
echo json_encode($arr);
}
else if($dayval == "Sun" && $date >= 18 && $date < 19) {
$timemax = 19;
$timeleft = ($timemax - $date);
if($timeleft == 1) {
$arr = array('tstatus' => 'Asian Market opening in less than ' .$timeleft. ' hour',
'tcode' => 'closed');
}
else {
$arr = array('tstatus' => 'Asian Market opening in less than ' .$timeleft. ' hours',
'tcode' => 'closed'
);
}
echo json_encode($arr);
I don't know if you have to apply any specific design pattern. Design patterns should only be used if you have a specific problem you are trying to solve, and the design pattern fills your need. I don't think you have such a problem here - I assume that your code works fine, in which case you can leave it like this.
Object Oriented Programming is not about applying design patterns to everything - much of your code will still be written similarly to your procedural style, but it will be oriented around your objects.
That said, I think that there is room for a bit of improvement here. Your repeat a fair bit of code here just to write hour / hours.
I would refactor that to look more like this:
$timeleft = ($timemax - $date);
$arr = array('tstatus' => 'Trading begins today at 6:00pm (less than '. $timeleft. ' hour' . ($timeleft == 1) ? '' : 's' . ' to go) - have a great trade week!',
'tcode' => 'closed'
);
That will add the 's' only if it is needed, without duplicating your code too much.
精彩评论