黑马程序员技术交流社区
标题:
单例模式设置属性问题
[打印本页]
作者:
jonn
时间:
2013-1-16 19:23
标题:
单例模式设置属性问题
interface Share
{
public float getArea() throws AreaException;
}
class AreaException extends Exception
{
protected AreaException(String msg){
super(msg);
}
}
abstract class ShareAbstract
{
private static final double PI=3.1415;
protected static double getPI(){
return PI;
}
}
class Rec extends ShareAbstract implements Share
{
private static int len;
private Rec(int len){
this.len=len;
}
private static Rec rec;
public static Rec getIntance(){
return rec=new Rec(len);
}
public void setLen(int len){
this.len=len;
}
public float getArea() throws AreaException{
if(len<0){
throw new AreaException("圆的半径 r < 0");
}
return (float)(ShareAbstract.getPI()*len*len);
}
}
class Square implements Share
{
private int len;
protected Square(int len){
this.setLen(len);
}
public void setLen(int len){
this.len=len;
}
public int getLen(){
return this.len;
}
public float getArea() throws AreaException{
if(len<0){
throw new AreaException("正方形的边长小于零");
}
return (float)(len*len);
}
}
class ShareDemo
{
public static void doGet(Share share){
try{
System.out.println(share.getArea());
}catch(AreaException e){
System.out.println("e.getMessage()");
}
}
public static void main(String[] args)
{
Rec.getIntance().setLen(4); //使用单例无法修改 Rec的属性 len, 求解决....
doGet(Rec.getIntance());
}
}
复制代码
作者:
jonn
时间:
2013-1-16 22:34
没人答? 自己解决了额
修改部分代码
private Rec(int len) {
this.setLen(len);
}
作者:
王溢君
时间:
2013-1-16 22:39
呵呵,自己解决了才是最好。。
作者:
李海鹏
时间:
2013-1-17 08:27
private static int len;
这是静态,没有赋初值可以通过,我觉得为了减少代码,直接改成public不就好了么
作者:
jonn
时间:
2013-1-17 10:25
李海鹏 发表于 2013-1-17 08:27
private static int len;
这是静态,没有赋初值可以通过,我觉得为了减少代码,直接改成public不就好了么 ...
这样做就是封装,达到外部无法访问的目的
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2