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

Detailed explanation of implementing simple factory pattern in Java

黄舟
黄舟Original
2017-09-29 10:10:041746browse

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();
}

2.Concrete class

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

3.Concrete class

public class Girl extends People{

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

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;
    }
  }
}

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();
  }
}

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!

Statement:
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