欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

设计模式学习之工厂方法模式

程序员文章站 2024-01-10 08:58:40
...

1.名词解释

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

 

2.代码示例

工厂接口
package DesignPattern.FactoryMethodPattern;

public interface IFactory {
	
	public Operation createOperation() ;
}

 

加法工厂
package DesignPattern.FactoryMethodPattern;

public class AddFactory implements IFactory {

	@Override
	public Operation createOperation() {
		return new AddOperation();
	}

}

 

乘法工厂
package DesignPattern.FactoryMethodPattern;

public class MulFactory implements IFactory {

	@Override
	public Operation createOperation() {
		return new MulOperation();
	}
}

 

package DesignPattern.FactoryMethodPattern;

public class Operation {

	private double numberA = 0.0d;
	private double numberB = 0.0d;
	
	public void setNumberA(double d) {
		this.numberA = d;
	}
	
	public double getNumberA() {
		return this.numberA;
	}
	
	public void setNumberB(double d) {
		this.numberB = d;
	}
	
	public double getNumberB() {
		return this.numberB;
	}
	
	public double getResult() {
		return 0.0;
	}
}

 

加法处理类
package DesignPattern.FactoryMethodPattern;

public class AddOperation extends Operation {

	public double getResult() {
		return super.getNumberA() + super.getNumberB();
	}
}

 

乘法处理类
package DesignPattern.FactoryMethodPattern;

public class MulOperation extends Operation{

	public double getResult() {
		return super.getNumberA() * super.getNumberB();
	}
}

 

 

主控程序
package DesignPattern.FactoryMethodPattern;

public class Client {

	public static void main(String[] args) {
		IFactory factory = new AddFactory();
		Operation operation = factory.createOperation();
		double numberA = 2;
		double numberB = 12.9;
		operation.setNumberA(numberA);
		operation.setNumberB(numberB);
		double result = operation.getResult();
		System.out.println(result);
		
		factory = new MulFactory();
	    operation = factory.createOperation();
	    operation.setNumberA(numberA);
		operation.setNumberB(numberB);
	    result = operation.getResult();
	    System.out.println(result);
	}
}

 

相关标签: 工厂方法