[关键字]:java,design pattern,设计模式,《Java与模式》学习,Immutable Pattern,不变模式
[环境]:StarUML5.0 + JDK6
[作者]:Winty (wintys@gmail.com) http://www.blogjava.net/wintys/
[正文]:
package pattern.immutable;
import java.text.NumberFormat;
/**
* 不变模式:Immutable Pattern
*
* 复数的四则运算
* @version 2009-6-15
* @author Winty(wintys@gmail.com)
*/
public class ImmutableTest{
public static void main(String[] args){
Complex a , b , c , d , e , f , g;
a = new Complex(0 , 2);
b = new Complex(3 , -5);
c = a.add(b);
d = a.sub(b);
e = a.mul(b);
f = a.div(b);
g = a.add(Complex.i);
System.out.println("a="+a);
System.out.println("b="+b);
System.out.println("i="+Complex.i);
System.out.println("a+b="+c);
System.out.println("a-b="+d);
System.out.println("a*b="+e);
System.out.println("a/b="+f);
System.out.println("a+i="+g);
}
}
final class Complex extends Number{
private double real;//实部
private double imaginary;//虚部
public static final Complex i;//虚数单位
static{
i = new Complex(0 , 1);
}
public Complex(){
real = 0.0;
imaginary = 0.0;
}
public Complex(double real , double imaginary){
this.real = real;
this.imaginary = imaginary;
}
public double getReal(){
return real;
}
public double getImaginary(){
return imaginary;
}
/**
* 复数相加
*/
public Complex add(Complex c){
return new Complex(real + c.getReal() ,
imaginary + c.getImaginary());
}
/**
* 复数相减
*/
public Complex sub(Complex c){
return new Complex(real - c.getReal() ,
imaginary - c.getImaginary());
}
/**
* 复数相乘:(a+bi)(c+di)=(ac-bd)+(ad+bc)i
*/
public Complex mul(Complex c){
double r = c.getReal();
double i = c.getImaginary();
r = real*r - imaginary*i;
i = real*i + imaginary*r;
return new Complex(r , i);
}
/**
* 复数除法:
* (a+bi)(c+di) = (a*c + b*d)/(c*c+d*d) + (b*c - a*d)/(c*c+d*d)
*/
public Complex div(Complex complex){
double a,b,c,d;
double denominator;
a = real;
b = imaginary;
c = complex.getReal();
d = complex.getImaginary();
denominator = c*c + d*d;
double r = (a*c + b*d)/denominator;
double i = (b*c - a*d)/denominator;
return new Complex(r , i);
}
public double abs(){
return Math.sqrt(real*real + imaginary*imaginary);
}
@Override
public double doubleValue(){
return real;
}
@Override
public float floatValue(){
return (float)real;
}
@Override
public int intValue(){
return (int)real;
}
@Override
public long longValue(){
return (long)real;
}
public String toString(){
NumberFormat f = NumberFormat.getNumberInstance();
f.setMaximumFractionDigits(2);
String strReal = f.format(real);
String strImaginary = f.format(imaginary);
String str = "";
String sign = "";
if(real != 0){//实部不为0时才显示实部
str = strReal;
if(imaginary > 0)
sign = "+";
}
str += sign + strImaginary + "*i";
return str;
}
}
运行结果:
a=2*i
b=3-5*i
i=1*i
a+b=3-3*i
a-b=-3+7*i
a*b=10+20*i
a/b=-0.29+0.18*i
a+i=3*i
原创作品,转载请注明出处。
作者:Winty (wintys@gmail.com)
博客:http://www.blogjava.net/wintys
posted on 2009-06-16 22:52
天堂露珠 阅读(985)
评论(0) 编辑 收藏 所属分类:
Pattern