黑马程序员技术交流社区

标题: 单例模式设置属性问题 [打印本页]

作者: jonn    时间: 2013-1-16 19:23
标题: 单例模式设置属性问题
  1. interface Share
  2. {
  3.         public float getArea() throws AreaException;
  4. }
  5. class AreaException extends Exception
  6. {
  7.         protected AreaException(String msg){
  8.                 super(msg);
  9.         }
  10. }
  11. abstract class ShareAbstract
  12. {
  13.     private static final double PI=3.1415;
  14.         protected static double getPI(){
  15.                 return PI;
  16.         }
  17. }
  18. class Rec extends ShareAbstract implements Share
  19. {
  20.          private static int len;
  21.          private Rec(int len){
  22.             this.len=len;
  23.          }
  24.          private static Rec rec;
  25.          public static Rec getIntance(){
  26.                  return rec=new Rec(len);
  27.          }
  28.          public void setLen(int len){
  29.                  this.len=len;
  30.          }
  31.          public float getArea() throws AreaException{
  32.                  if(len<0){
  33.            throw new AreaException("圆的半径 r < 0");
  34.                  }
  35.        return (float)(ShareAbstract.getPI()*len*len);
  36.          }
  37. }
  38. class Square implements Share
  39. {
  40.          private int len;
  41.          protected Square(int len){
  42.                  this.setLen(len);
  43.          }
  44.          public void setLen(int len){
  45.                  this.len=len;
  46.          }
  47.          public int  getLen(){
  48.                  return this.len;
  49.          }
  50.          public float getArea() throws AreaException{
  51.          if(len<0){
  52.                          throw new AreaException("正方形的边长小于零");
  53.                  }
  54.                  return (float)(len*len);
  55.          }
  56. }
  57. class ShareDemo
  58. {
  59.           public static void doGet(Share share){
  60.                   try{
  61.                System.out.println(share.getArea());
  62.                   }catch(AreaException e){
  63.               System.out.println("e.getMessage()");
  64.                   }
  65.                 }

  66.         public static void main(String[] args)
  67.         {     
  68.                 Rec.getIntance().setLen(4);  //使用单例无法修改 Rec的属性 len, 求解决....
  69.                 doGet(Rec.getIntance());
  70.         }
  71. }
复制代码

作者: 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