当前位置:编程学习 > C/C++ >>

工厂模式(Factory Method)

工厂设计模式:定义一个用于创建对象的接口,让子类决定实例化那个类,工厂方法使一个类的实例化延迟到其子类

 

 

 

简单案例(加法计算器)

//加减乘除操作工厂


[java]
public inte易做图ce OperationInte易做图ce { 
    public double operate(int a,int b); 

public inte易做图ce OperationInte易做图ce {
    public double operate(int a,int b);
}
//创建加减乘除的工厂
[java]
public inte易做图ce FactoryInteface{ 
    public OperationInte易做图ce CreateFactory(); 

public inte易做图ce FactoryInteface{
    public OperationInte易做图ce CreateFactory();
}//加法操作类
[java] 
public class OperationAdd implements OperationInte易做图ce { 
 
    @Override 
    public double operate(int a, int b) { 
        return a+b; 
    } 
     

public class OperationAdd implements OperationInte易做图ce {

    @Override
    public double operate(int a, int b) {
        return a+b;
    }
   
}//创建加法这一操作的工厂


[java] 
public class FactoryAdd implements FactoryInteface{ 
 
    @Override 
    public OperationInte易做图ce CreateFactory() { 
        return new OperationAdd(); 
    } 

public class FactoryAdd implements FactoryInteface{

    @Override
    public OperationInte易做图ce CreateFactory() {
        return new OperationAdd();
    }
}//主函数调用
[java
public class Factory { 
    public static void main(String[] arg) 
    { 
        FactoryAdd factoryAdd = new FactoryAdd(); 
        OperationInte易做图ce add =  factoryAdd.CreateFactory(); 
        System.out.println(add.operate(23, 123)); 
    } 

public class Factory {
    public static void main(String[] arg)
    {
        FactoryAdd factoryAdd = new FactoryAdd();
        OperationInte易做图ce add =  factoryAdd.CreateFactory();
        System.out.println(add.operate(23, 123));
    }
}

 

补充:软件开发 , C++ ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,