Home >Java >javaTutorial >Simple example of JAVA factory pattern

Simple example of JAVA factory pattern

高洛峰
高洛峰Original
2016-12-15 14:37:101263browse

Now we give a simple use case to simulate a ham production factory. The factory can produce several types of Ham. After creating a factory instance, you only need to tell it what kind of Ham you want to produce, and it will give you You produce:
package test;

interface Ham { //Define the interface to assist in implementing the factory mode
  void show();//Various Hams produced by the Ham factory will have the ability to show()
}
public class FatoryModule {//Factory class, used to produce many different types of Ham
​​ public Ham getHam(String HamType) throws Exception{//The action of the factory class object to produce Ham
​​​if (HamType.equals("HamA") ) {
              return new HamA(); Type.equals("HamC")) {
                return new HamC(); ] args) {//Test code
                                                                                                        using   using using using use using using           through using ‐ ‐ ‐ ` ‐ ‐ args) { The modification amount reaches the minimum
                                                                                                                                    myHam.show(); A product produced by HamA
  public void show() {
      System.out.println("You got a HamA.");
  }
}

class HamB implements Ham { //Another product produced by the factory HamB V Public void show () {
system.out.println ("you get a hamb."); {
              System.out.println("You got a HamC.");

                                         using       using using ’ s ‐ to use ’ s           through ’'s  ‐  ‐  ‐                 out out out out out out through out out through out through out using ‐ ‐ to ‐ ‐‐‐‐‐‐                 You can get this type of Ham by planting any kind of Ham (that is, the parameters in the getHam() method) without writing HamX hamX=new HamX(); If there are dozens of different Ham objects that need to be used in different places in the program Create, then using the factory pattern code will appear simple and unified. Every place that requires a different Ham is only the parameters of getHam(). Otherwise, once the program needs to be expanded and maintained, dozens of new statements will cause headaches. And if you need to add a new Ham type, you only need to add it in the factory class.








For more simple examples of JAVA factory pattern, please pay attention to the PHP Chinese website for related articles!

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