English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Использует ли статический фабричный метод ключевое слово new для создания объектов в Java?

Фабричный метод — это шаблон дизайна (шаблон творчества), который используется для создания множества объектов на основе предоставленных данных. В нем мы создаем объект абстрактного процесса создания.

Example

Ниже приведен пример реализации фабричного метода. Здесь у нас есть интерфейс Employee и 3 класса:StudentУчителя,NonTeachingStaffРеализовал его. Мы создали фабричный класс (EmployeeFactory) с именем.getEmployee()Этот метод принимает значение String и возвращает объект одного из классов в зависимости от предоставленного значения String.

import java.util.Scanner;
interface Person{}}
   void dsplay();
}
class Student implements Person{
   public void dsplay() {
      System.out.println("This is display method of the Student class");
   }
}
class Lecturer implements Person{
   public void dsplay() {
      System.out.println("This is display method of the Lecturer class");
   }
}
class NonTeachingStaff implements Person{
   public void dsplay() {
      System.out.println("This is display method of the NonTeachingStaff class");
   }
}
class PersonFactory{
   public Person getPerson(String empType) {
      if(empType == null){
         return null;
      }
      if(empType.equalsIgnoreCase("student")){
         return new Student();
      } else if(empType.equalsIgnoreCase("lecturer")){
         return new Lecturer();
      } else if(empType.equalsIgnoreCase("non teaching staff")){
         return new NonTeachingStaff();
      }
      return null;
   }
}
public class FactoryPattern {
   public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Введите тип объекта, который вы хотите: (student, lecturer, non teaching staff)");
      String type = sc.next();
      PersonFactory obj = new PersonFactory();
      Person emp = obj.getPerson(type);
      emp.dsplay();
   }
}

Результат вывода

Введите тип объекта, который вы хотите: (student, lecturer, non teaching staff)
lecturer
Это метод отображения класса Lecturer

Static factory method

Although it is said that there are five methods to create objects in Java-

  • Using the new keyword.

  • Using the factory method.

  • Using cloning.

  • Using Class.forName().

  • Using object deserialization.

The only way to create an object in Java is to use the new keyword, and all other methods are abstractions of the object. All these methods internally use the new keyword completely.

Example

import java.util.Scanner;
interface Employee{
   void dsplay();
}
class Student implements Employee{
   public void dsplay() {
      System.out.println("This is display method of the Student class");
   }
}
class Lecturer implements Employee{
   public void dsplay() {
      System.out.println("This is display method of the Lecturer class");
   }
}
class NonTeachingStaff implements Employee{
   public void dsplay() {
      System.out.println("This is display method of the NonTeachingStaff class");
   }
}
class EmployeeFactory{
   public static Employee getEmployee(String empType) {
      if(empType == null){
         return null;
      }
      if(empType.equalsIgnoreCase("student")){
         return new Student();
      } else if(empType.equalsIgnoreCase("lecturer")){
         return new Lecturer();
      } else if(empType.equalsIgnoreCase("non teaching staff")){
         return new NonTeachingStaff();
      }
      return null;
   }
}
public class FactoryPattern {
   public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Введите тип объекта, который вы хотите: (student, lecturer, non teaching staff)");
      String type = sc.next();
      EmployeeFactory obj = new EmployeeFactory();
      Employee emp = EmployeeFactory.getEmployee(type);
      emp.dsplay();
   }
}

Результат вывода

Введите тип объекта, который вы хотите: (student, lecturer, non teaching staff)
lecturer
Это метод отображения класса Lecturer
Вам может понравиться