Get the App
SLTechnology News&Howtos  ›  Development  › 

Java simple factory, factory method, how to implement abstract factory pattern

Shulou Source: shulou.com Published: 2022-06-01 12:58:54 10月03日 Update

This article mainly explains the "Java simple factory, factory method, abstract factory pattern how to achieve", the content of the article is simple and clear, easy to learn and understand, the following please follow the editor's ideas slowly in depth, together to study and learn "Java simple factory, factory method, abstract factory pattern how to achieve" it!

1. Simple factory model 1. Define

Simple factory pattern (Simple Factory Pattern) means that an instance of a product class is determined by a factory object.

It belongs to the creative pattern, but it does not belong to the GOF23 design pattern.

two。 Code case

Let's take the manufacturing of canned products as a case study.

Step 1: define the top-level interface class ICanned for cans

/ * @ Package: com.hzg.study.design.pattern.factory.simplefactory * @ Description: interface on the top level of cans * @ Author: HuangZhiGao * @ CreateDate: 2022-02-17 17:52 * / public interface ICanned {/ * display the name of cans * @ return void * @ author HuangZhiGao * @ date 2022 2Gash 1717 17:54 * / void showCannedName ();}

Step 2: write two specific implementation classes FruitCanned and BeefCanned respectively

/ * * @ Package: com.hzg.study.design.pattern.factory.simplefactory * @ Description: canned fruit * @ Author: HuangZhiGao * @ CreateDate: 2022-02-17 17:56 * / public class FruitCanned implements ICanned {@ Override public void showCannedName () {System.out.println ("name: canned fruit") } / * * @ Package: com.hzg.study.design.pattern.factory.simplefactory * @ Description: canned beef * @ Author: HuangZhiGao * @ CreateDate: 2022-02-17 17:57 * / public class BeefCanned implements ICanned {@ Override public void showCannedName () {System.out.println ("name: canned beef");}}

Step 3: write the factory class

Import com.hzg.study.design.pattern.factory.common.ICanned / * @ Package: com.hzg.study.design.pattern.factory.simplefactory * @ Description: cannery class * @ Author: HuangZhiGao * @ CreateDate: 2022-02-17 18:16 * / public class CannedFactory {/ * method for creating cans * @ param clazz * @ return com.hzg.study.design.pattern.factory.common.ICanned * @ author HuangZhiGao * @ date 2022 * public ICanned createCanned (Class)

Tags: Factory can pattern information product interface label method material beef fruit object canned fruit code name product family top level upgrade instance upgrade Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Tech Info OPPO Reno MariaDB Redmi Huawei