开发者社区> 问答> 正文

java中多例模式有哪些特点及如何举例?

已解决

java中多例模式有哪些特点及如何举例?

展开
收起
游客gzyuldo4mrg6i 2022-04-03 16:59:56 607 0
1 条回答
写回答
取消 提交回答
  • 推荐回答

    举例: package com.pers.hoobey;

    import java.util.ArrayList;

    import java.util.List;

    import java.util.Random;

    public class Car1 {

      private static Car1 car1 = new Car1();

      private static Car1 car2 = new Car1();

      private static List list = new ArrayList ();//用于存放多个实例的car

      private static final int maxCount =2;//最多的实例数

      static{
    

        list.add(car1);

        list.add(car2);

      }

      private Car1(){}//私有构造方法 避免外部创建实例

    /*

    * @description 指定拿取某一个实例
    

    */

      public static Car1 getInstance(int index){

        return list.get(index);

      }

      //随机拿取实例

      public static Car1 getInstance(){
    

        Random random = new Random();

        int current = random.nextInt(maxCount);

        return list.get(current);

    }
    
    public void run(){
    
    System.out.println("奔跑中的车.....");
    
    }
    

    }

    2022-04-03 17:05:49
    赞同 展开评论 打赏
问答分类:
问答标签:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
Spring Cloud Alibaba - 重新定义 Java Cloud-Native 立即下载
The Reactive Cloud Native Arch 立即下载
JAVA开发手册1.5.0 立即下载