Advertisement
Guest User

Untitled

a guest
May 29th, 2015
246
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.01 KB | None | 0 0
  1. Example: Creating Subclasses with a String
  2. So far I do not have a great gain; the advantage comes from the fact that I have separated the receiver of the creation call from the class of object created. If I later apply Replace Type Code with Subclasses (Organizing Data) to turn the codes into subclasses of employee, I can hide these subclasses from clients by using the factory method:
  3. ```
  4. static Employee create(int type) {
  5. switch (type) {
  6. case ENGINEER:
  7. return new Engineer();
  8. case SALESMAN:
  9. return new Salesman();
  10. case MANAGER:
  11. return new Manager();
  12. default:
  13. throw new IllegalArgumentException("Incorrect type code value");
  14. }
  15. }
  16. ```
  17. The sad thing about this is that I have a switch. Should I add a new subclass, I have to remember to update this switch statement, and I tend toward forgetfulness.
  18.  
  19. A good way around this is to use Class.forName. The first thing to do is to change the type of the parameter, essentially a variation on Rename Method. First I create a new method that takes a string as an argument:
  20. ```
  21. static Employee create (String name) {
  22. try {
  23. return (Employee) Class.forName(name).newInstance();
  24. } catch (Exception e) {
  25. throw new IllegalArgumentException ("Unable to instantiate" + name);
  26. }
  27. }
  28. ```
  29. I then convert the integer create to use this new method:
  30. ```
  31. class Employee {
  32. static Employee create(int type) {
  33. switch (type) {
  34. case ENGINEER:
  35. return create("Engineer");
  36. case SALESMAN:
  37. return create("Salesman");
  38. case MANAGER:
  39. return create("Manager");
  40. default:
  41. throw new IllegalArgumentException("Incorrect type code value");
  42. }
  43. }
  44. ```
  45. I can then work on the callers of create to change statements such as
  46. ```
  47. Employee.create(ENGINEER)
  48. ```
  49. to
  50. ```
  51. Employee.create("Engineer")
  52. ```
  53. When I'm done I can remove the integer parameter version of the method.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement