换成工厂方法模式

    1. {
    2. public function CreateOperation();
    3. }
    4. class AddFactory implements IFactory
    5. {
    6. public function CreateOperation()
    7. {
    8. return new OperationAdd();
    9. }
    10. }
    11. public function CreateOperation()
    12. {
    13. return new OperationSub();
    14. }
    15. }
    16. class MulFactory implements IFactory
    17. {
    18. public function CreateOperation()
    19. {
    20. return new OperationMul();
    21. }
    22. class DivFactory implements IFactory
    23. {
    24. public function CreateOperation()
    25. {
    26. return new OperationDiv();
    27. }
    28. }
    29. //客户端代码
    30. $operationFactory = new AddFactory();
    31. $operation = $operationFactory->CreateOperation();
    32. $operation->setA(10);

    下一章: