Home > Java > javaTutorial > Detailed explanation of implementing simple factory pattern in Java

Detailed explanation of implementing simple factory pattern in Java

黄舟
Release: 2017-09-29 10:10:04
Original
1747 people have browsed it

This article mainly introduces the relevant information of the simple factory pattern of java design pattern, which has certain reference value. Interested friends can refer to it

Simple factory pattern: determined by a factory object Which type of instance is created.

1.Abstract class

public abstract class People {
  public abstract void doSth();
}
Copy after login

2.Concrete class

public class Man extends People{
  @Override
  public void doSth() {
    System.out.println("I'm a man,I'm coding.");
  }
}
Copy after login

3.Concrete class

public class Girl extends People{

  @Override
  public void doSth() {
    System.out.println("I'm a girl,I'm eating.");
  }
}
Copy after login

4.Factory

public class PeopleFactory {

  public static People getSpecificPeople(String type){
    if("A-Man".equals(type)){
      return new Man();
    }else if("B-Girl".equals(type)){
      return new Girl();
    }else {
      return null;
    }
  }
}
Copy after login

5.Test Code

public class PeopleTestDemo {
  public static void main(String[] args) {
    People man = PeopleFactory.getSpecificPeople("A-Man");
    Objects.requireNonNull(man,"对象不存在.");
    man.doSth();

    People girl = PeopleFactory.getSpecificPeople("B-Girl");
    Objects.requireNonNull(girl,"对象不存在");
    girl.doSth();

    People foodie = PeopleFactory.getSpecificPeople("Foodie");
    Objects.requireNonNull(foodie,"对象不存在");
    foodie.doSth();
  }
}
Copy after login

The above is the detailed content of Detailed explanation of implementing simple factory pattern in Java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template