设计模式【三】策略模式

1、类图

2、实现

主要解决输入相近,不同算法计算输出的问题

 public abstract class AbstractExport {

    protected String exportType;

    public abstract void export(String str);

}

public class AsyncExport extends AbstractExport {

    public AsyncExport() {
        super.exportType = "ASYNC";
    }

    @Override
    public void export(String str) {
        System.out.println("export type:" + super.exportType + ";str:" + str);
    }
}

public class SyncExport extends AbstractExport {

    public SyncExport() {
        super.exportType = "SYNC";
    }

    @Override
    public void export(String str) {
        System.out.println("export type:" + super.exportType + ";str:" + str);
    }
}

public class NormalExport extends AbstractExport {

    public NormalExport() {
        super.exportType = "NORMAL";
    }

    @Override
    public void export(String str) {
        System.out.println("export type:" + super.exportType + ";str:" + str);
    }
}

public class Context {

    private AbstractExport abstractExport;

    public Context(AbstractExport abstractExport) {
        this.abstractExport = abstractExport;
    }

    public void export(String str) {
        this.abstractExport.export(str);
    }
}

public class ExportTest {

    public static void main(String[] args) throws IllegalAccessException, InstantiationException, ClassNotFoundException {
        String str = "test";
        AbstractExport export = new SyncExport();
        Context context = new Context(export);
        context.export(str);

        AbstractExport exportClass = (AbstractExport) Class.forName(SyncExport.class.getName()).newInstance();
        Context contextReflect = new Context(exportClass);
        contextReflect.export(str);
    }

}

   转载规则


《设计模式【三】策略模式》 Euler 采用 知识共享署名 4.0 国际许可协议 进行许可。
  目录