首页 > 其他分享 >1) Factory method pattern

1) Factory method pattern

时间:2023-06-06 13:36:03浏览次数:47  
标签:draw pattern class Factory method Shape 子类 public

类别:

 Creational Pattern

问题/动机

如何创建一套子类的问题(父类引用指向子类实例)

情形1:一个方法返回一个具体的子类

极端情况:1万个子类需要一万个方法吗

极端情况:如过再扩展一万个子类,还需要再增加一万个方法吗

极端情况:虽然有一万个子类,但只需要用到其中一个,其他9999个干陪着吗

情形2:一个方法返回一个父类

不管有多少子类,都可以用一个方法将其返回,可以通过一定的策略和配置文件达到不修改client的目的

方案

 

示例

/* 测试方法 */
public class FactoryPatternDemo {
    public static void main(String[] args) {
        Shape shape1 = ShapeFactory.getShape("CIRCLE");
        shape1.draw();
        Shape shape2 = ShapeFactory.getShape("RECTANGLE");
        shape2.draw();
        Shape shape3 = ShapeFactory.getShape("SQUARE");
        shape3.draw();
    }
}

/* 工厂返回类型,子类对象赋给父类引用 (向上转型) */
interface Shape {
    void draw();
}

/* 矩形 */
class Rectangle implements Shape {
    @Override
    public void draw() {
        System.out.println("Inside Rectangle::draw() method.");
    }

}

/* 正方形 */
class Square implements Shape {
    @Override
    public void draw() {
        System.out.println("Inside Square::draw() method.");
    }
}

/* 圆 */
class Circle implements Shape {
    @Override
    public void draw() {
        System.out.println("Inside Circle::draw() method.");
    }
}

/* 简单工厂 */
class ShapeFactory {
    public static Shape getShape(String shapeType) {
        if (shapeType == null) {
            return null;
        }
        if (shapeType.equalsIgnoreCase("CIRCLE")) {
            return new Circle();
        } else if (shapeType.equalsIgnoreCase("RECTANGLE")) {
            return new Rectangle();
        } else if (shapeType.equalsIgnoreCase("SQUARE")) {
            return new Square();
        }
        return null;
    }
}

 

Inside Circle::draw() method.
Inside Rectangle::draw() method.
Inside Square::draw() method.

 

优化

抽象工厂模式 

关键词

向上转型,简单参数

应用

package org.slf4j;
[...]
public final class LoggerFactory {
[...]
    public static Logger getLogger(String name) {
        ILoggerFactory iLoggerFactory = getILoggerFactory();
        return iLoggerFactory.getLogger(name);
    }
[...]
}

 

补充

静态工厂方法,见《Effective Java》

获取加密算法:

https://docs.oracle.com/javase/7/docs/technotes/guides/security/StandardNames.html#KeyPairGenerator

import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;

public class Test {
    
    public static void main(String[] args) throws NoSuchAlgorithmException {
        KeyPairGenerator instance = KeyPairGenerator.getInstance("RSA");
    }
}

获取证书工厂:

https://docs.oracle.com/javase/7/docs/api/java/security/cert/CertificateFactory.html

import java.security.cert.CertificateFactory;

public class Test {
    public static void main(String[] args) throws Exception {
        CertificateFactory instance = CertificateFactory.getInstance("X.509");
    }
}

 

获取MXBean 

java.lang.management.ManagementFactory.getMemoryMXBean()

 

标签:draw,pattern,class,Factory,method,Shape,子类,public
From: https://www.cnblogs.com/zno2/p/6694783.html

相关文章

  • 9) Composite Pattern
    类别: StructualPattern问题: 方案:   示例: importjava.util.ArrayList;importjava.util.List;publicclassCompositePatternDemo{publicstaticvoidmain(String[]args){Bodysun=newBody("太阳","恒星",1392000000);......
  • 8) Filter/Criteria Pattern
    类别: StructualPattern问题: 方案:   示例: importjava.util.ArrayList;importjava.util.HashSet;importjava.util.List;importjava.util.Set;publicclassCriteriaPatternDemo{publicstaticvoidmain(String[]args){List<Person>p......
  • 7) Bridge Pattern
    类别: StructuralPatterns问题:连连看的问题 不使用桥接,要写81个类,使用桥接,只需要18个类方案: 示例: publicclassBridgePatternDemo{publicstaticvoidmain(String[]args){Somebodysb=newXiaohong(newBanana());sb.eat();......
  • 6) Adapter Pattern
    类别: StructuralPattern问题:什么是接口?按照标准提供服务,其他想要使用该接口的要按照该标准接入服务什么是依赖?持有目标对象,拥有使用权(AuseB)数据线?数据线按USB标准接入充电宝,通过lightning提供充电服务手机?通过lightning标准接入数据线  客户端因种种限制只能接入......
  • 10) Decorator Pattern
    类别: StructuralPattern问题: 在不改变接口的前提下增加额外的服务方案:   示例:publicclassDecoratorPatternDemo{publicstaticvoidmain(String[]args){Shapecircle=newCircle();ShaperedCircle=newRedShapeDecorator(newC......
  • 类GeometricShapeFactory-JTS几何图形绘制API
    org.locationtech.jts.util类GeometricShapeFactoryjava.lang.Objectorg.locationtech.jts.util.GeometricShapeFactory直接已知子类:正弦之星工厂公共类GeometricShapeFactory扩展Object计算各种常见的几何形状。提供各种方法来指定所生成形状的位置,范围和旋转,以及用于形成它们......
  • drf:Method Not Allowed
    put请求,报错如题其中的urlurl(r'books/',views.BookView.as_view()),path('books/<int:pk>',views.BookView2.as_view())原因:第一条url后没加$,put请求被第一条url匹配到,第一个url是get和put,所以报错putnotallow......
  • cpp: Bridge Pattern
     /*****************************************************************//***\fileGold.h*\brief桥接模式BridgePatternC++14*2023年6月3日涂聚文GeovinDuVisualStudio2022edit.*\authorgeovindu*\dateJune2023***********************......
  • springboot项目rabbitmq消费者消费json格式的String,出现无限循环抛出No method found
    转:springboot项目rabbitmq消费者消费json格式的String,出现无限循环抛出Nomethodfoundforclass[B     ......
  • spring cloud gateway 自定义GatewayFilterFactory
    官网地址:https://docs.spring.io/spring-cloud-gateway/docs/2.2.9.RELEASE/reference/html/#writing-custom-route-predicate-factories参考地址:https://blog.csdn.net/myli92/article/details/127328893importcom.ruoyi.common.core.utils.StringUtils;importorg.springfr......