Answer to Question #256850 in Java | JSP | JSF for hatipo

Question #256850

The object’s creation may lead to a significant duplication of code, may require information not accessible to the composing object, may not provide a sufficient level of abstraction, or may otherwise not be part of the composing object’s concerns. The factory method design pattern handles these problems by defining a separate method for creating the objects, which subclasses can then override to specify the derived type of product that will be created. The factory method pattern relies on inheritance, as object creation is delegated to subclasses that implement the factory method to create objects.

Elves and Orcs are at war. They have various weapons that they use to fight, such as short swords, spears, and axes. We, the blacksmith in this world, need to ensure the manufactoring of these weapons. Remember that there are blacksmiths on both sides. But we don’t want to create all weapons as separate objects. That’s why we need a more effective method. Build your system using the factory method pattern.


1
Expert's answer
2021-10-27T00:47:57-0400
public class Main{
    public static void main(String[]args){
        Person[] p= new Person[50];
        for(int i=0;i<50;i++){
            p[i]=Person_factory.createMale(i);
        }
    }
}
class Person {
    int id;
    String gender;
    public Person(int i,String g){
        id=i;
        gender=g;
    }
    public int getID() {
        return id;
    }
    public String getGender() {
        return gender;
    }
}
class Person_factory{
    public static Person createMale(int id){
        return new Person(id,"M");
    }
    public static Person createFemale(int id){
        return new Person(id,"F");
    }
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS