静态工厂模式-反射工厂模式-注解工厂模式代码实现

1. 静态工厂


package top.zynorl.csdnDemo.factory;

/**
 * Created by zynorl on 2023/9/14 10:24
 */

class StaticFactory {
    private StaticFactory() {}
    static IBook getInstance(String className) {
        if ("math".equalsIgnoreCase(className)) {
            return new MathBook() ;
        } else if ("program".equalsIgnoreCase(className)) {
            return new ProgramBook() ;
        } else {
            return null ;
        }
    }
}

public class StaticFactoryTest {
    public static void main(String[] args) throws Exception {
        IBook book = StaticFactory.getInstance("program") ;
        book.read();
    }
}

2. 反射与工厂

package top.zynorl.csdnDemo.factory;

/**
 * Created by zynorl on 2023/9/14 10:41
 */

class ReflectFactory {
    private ReflectFactory() {}
    public static IBook getInstance(String className) { // 必须传递类的完整名称
        try { // 直接实例化对象
            Object obj = Class.forName(className).getDeclaredConstructor().newInstance();
            if (obj instanceof IBook) { // 为了防止出现ClassCastException
                return (IBook) obj ; // 强制性的向下转型
            }
            return null ;
        } catch (Exception e) {
            return null ;
        }
    }
}
public class ReflectFactoryTest {
    public static void main(String[] args) throws Exception {
        IBook book = ReflectFactory.getInstance("top.zynorl.csdnDemo.factory.ProgramBook") ;
        book.read();
    }
}

3. 注解与工厂

package top.zynorl.csdnDemo.factory;

import top.zynorl.csdnDemo.factory.annotation.Factory;
import top.zynorl.csdnDemo.factory.annotation.Instance;

/**
 * Created by zynorl on 2023/9/14 10:51
 */


interface IChannel extends AutoCloseable {
    public boolean build() ; // 建立通道
}
class InternetChannel implements IChannel {
    @Override
    public boolean build() {
        System.out.println("【InternetChannel】建立互联网通讯通道。");
        return true;
    }
    @Override
    public void close() throws Exception {
        System.out.println("【InternetChannel】关闭互联网通讯通道。");
    }
}
class RadioChannel implements IChannel {
    @Override
    public boolean build() {
        System.out.println("【RadioChannel】建立无线电通讯通道。");
        return true;
    }
    @Override
    public void close() throws Exception {
        System.out.println("【RadioChannel】关闭无线电通讯通道。");
    }
}
class AnnotationFactory { // 编写工厂类
    private AnnotationFactory() {}
    public static <T> T getInstance(String className) {
        try {   // 实现一个泛型工厂类
            return (T) Class.forName(className).getDeclaredConstructor().newInstance();
        } catch (Exception e) {
            return null ;
        }
    }
}
@Instance("top.zynorl.csdnDemo.factory.RadioChannel") // 通过注解配置了当前Message类所使用的通道信息
class Message { // 进行消息的发送处理
    private IChannel channel ; // 如果需要发送消息就必须提供通道
    @Factory("top.zynorl.csdnDemo.factory.AnnotationFactory")
    public Message() {  // 构造方法
        try {// 获取指定的注解配置的信息
            Instance InstanceAnnotation = super.getClass().getAnnotation(Instance.class) ; // 获取类上的Annotation
            Factory instanceAnnotation = super.getClass().getConstructor().getAnnotation(Factory.class); // 获取构造方法上的指定构造
            String factoryClassName = instanceAnnotation.value() ;
            Class factoryClazz = Class.forName(factoryClassName) ;
            this.channel = (IChannel) factoryClazz.getMethod("getInstance", String.class).invoke(null, InstanceAnnotation.value()) ;
        } catch (Exception e) {
            System.out.println(e);
        }
    }
    public String echo(String msg) throws Exception {
        String echoMessage = "〖ERROR〗消息发送失败!" ;
        if (this.channel.build()) { // 通道创建成功
            echoMessage = "【ECHO】" + msg ; // 创建回应信息
            this.channel.close();
        }
        return echoMessage ;
    }
}
public class AnnotationFactoryTest{
    public static void main(String[] args) throws Exception {
        System.out.println(new Message().echo("注解工厂模式"));
    }
}

4. 附录

public interface IBook {
    void read() ;
}
class MathBook implements IBook {
    @Override
    public void read() {
        System.out.println("数学书");
    }
}
class ProgramBook implements IBook {
    @Override
    public void read() {
        System.out.println("编程书");
    }
}
/**
 * Created by zynorl on 2023/9/14 10:55
 */

@Target({ElementType.CONSTRUCTOR}) // 此注解可以应用在类定义上
@Retention(RetentionPolicy.RUNTIME) // 在当前执行的时候此Annotation生效
public @interface Factory { // 指定工厂
    public String value() ; // value可以避免编写变量名称
}
/**
 * Created by zynorl on 2023/9/14 10:55
 */

@Target({ElementType.CONSTRUCTOR}) // 此注解可以应用在类定义上
@Retention(RetentionPolicy.RUNTIME) // 在当前执行的时候此Annotation生效
public @interface Factory { // 指定工厂
    public String value() ; // value可以避免编写变量名称
}

你可能感兴趣的:(java,java)