Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Example: Creating Subclasses with a String
- 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:
- ```
- static Employee create(int type) {
- switch (type) {
- case ENGINEER:
- return new Engineer();
- case SALESMAN:
- return new Salesman();
- case MANAGER:
- return new Manager();
- default:
- throw new IllegalArgumentException("Incorrect type code value");
- }
- }
- ```
- 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.
- 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:
- ```
- static Employee create (String name) {
- try {
- return (Employee) Class.forName(name).newInstance();
- } catch (Exception e) {
- throw new IllegalArgumentException ("Unable to instantiate" + name);
- }
- }
- ```
- I then convert the integer create to use this new method:
- ```
- class Employee {
- static Employee create(int type) {
- switch (type) {
- case ENGINEER:
- return create("Engineer");
- case SALESMAN:
- return create("Salesman");
- case MANAGER:
- return create("Manager");
- default:
- throw new IllegalArgumentException("Incorrect type code value");
- }
- }
- ```
- I can then work on the callers of create to change statements such as
- ```
- Employee.create(ENGINEER)
- ```
- to
- ```
- Employee.create("Engineer")
- ```
- When I'm done I can remove the integer parameter version of the method.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement