java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Java创建类实例模式

Android/Java中创建类实例的各种模式实例代码

作者:沪cares

这篇文章主要介绍了Android/Java中创建类实例各种模式的相关资料,包括New关键字、静态工厂方法、建造者模式、单例模式、依赖注入、抽象工厂模式、原型模式和Reflection,每个模式有其特点和适用场景,需要的朋友可以参考下

创建型模式总览

模式名称核心思想使用频率难度
new 关键字直接调用构造函数⭐⭐⭐⭐⭐
静态工厂方法通过静态方法创建实例⭐⭐⭐⭐⭐⭐
建造者模式分步构建复杂对象⭐⭐⭐⭐⭐⭐
单例模式确保全局唯一实例⭐⭐⭐⭐⭐⭐
依赖注入外部容器管理依赖⭐⭐⭐⭐⭐⭐⭐⭐
抽象工厂模式创建相关对象家族⭐⭐⭐⭐⭐⭐
原型模式通过克隆创建实例⭐⭐⭐
反射创建运行时动态创建⭐⭐⭐⭐

1. new 关键字 (Direct Instantiation)

名词解释

最基础的实例创建方式,直接调用类的构造函数来创建对象实例。

核心特点

// 基本语法
ClassName object = new ClassName(arguments);

// 示例
User user = new User("Alice", 25);
TextView textView = new TextView(context);

优点

缺点

适用场景

Android 示例

// 创建基础UI组件
TextView textView = new TextView(context);
Button button = new Button(context);

// 创建数据对象
Intent intent = new Intent(context, MainActivity.class);
Bundle bundle = new Bundle();

2. 静态工厂方法 (Static Factory Method)

名词解释

通过类的静态方法来创建实例,而不是直接调用构造函数。

核心特点

public class Connection {
    private String url;
    
    private Connection(String url) {
        this.url = url;
    }
    
    // 静态工厂方法
    public static Connection create(String url) {
        validateUrl(url); // 添加验证逻辑
        return new Connection(url);
    }
    
    // 有名称的工厂方法
    public static Connection createSecureConnection() {
        return new Connection("https://secure.example.com");
    }
}

// 使用
Connection conn = Connection.create("https://api.example.com");

优点

缺点

适用场景

Android 示例

// Intent 工厂方法
Intent chooserIntent = Intent.createChooser(shareIntent, "Share via");

// Bitmap 工厂方法
Bitmap bitmap = Bitmap.createBitmap(100, 100, Bitmap.Config.ARGB_8888);

// Uri 解析
Uri uri = Uri.parse("content://com.example.provider/data");

3. 建造者模式 (Builder Pattern)

名词解释

通过一个建造者类来分步构建复杂对象,特别适合参数多的场景。

核心特点

public class AlertDialogConfig {
    private final String title;
    private final String message;
    private final boolean cancelable;
    
    private AlertDialogConfig(Builder builder) {
        this.title = builder.title;
        this.message = builder.message;
        this.cancelable = builder.cancelable;
    }
    
    public static class Builder {
        private String title;
        private String message;
        private boolean cancelable = true;
        
        public Builder setTitle(String title) {
            this.title = title;
            return this;
        }
        
        public Builder setMessage(String message) {
            this.message = message;
            return this;
        }
        
        public Builder setCancelable(boolean cancelable) {
            this.cancelable = cancelable;
            return this;
        }
        
        public AlertDialogConfig build() {
            return new AlertDialogConfig(this);
        }
    }
}

// 使用
AlertDialogConfig config = new AlertDialogConfig.Builder()
    .setTitle("Warning")
    .setMessage("Are you sure?")
    .setCancelable(false)
    .build();

优点

缺点

适用场景

Android 示例

// Notification 建造者
Notification notification = new NotificationCompat.Builder(context, "channel_id")
    .setContentTitle("Title")
    .setContentText("Message")
    .setSmallIcon(R.drawable.ic_notification)
    .build();

// Retrofit 建造者
Retrofit retrofit = new Retrofit.Builder()
    .baseUrl("https://api.example.com/")
    .addConverterFactory(GsonConverterFactory.create())
    .build();

4. 单例模式 (Singleton Pattern)

名词解释

确保一个类只有一个实例,并提供全局访问点。

核心特点

// 双重检查锁实现
public class AppManager {
    private static volatile AppManager instance;
    private final Context appContext;
    
    private AppManager(Context context) {
        this.appContext = context.getApplicationContext();
    }
    
    public static AppManager getInstance(Context context) {
        if (instance == null) {
            synchronized (AppManager.class) {
                if (instance == null) {
                    instance = new AppManager(context);
                }
            }
        }
        return instance;
    }
}

// 静态内部类实现(推荐)
public class DatabaseHelper {
    private DatabaseHelper() {}
    
    private static class Holder {
        static final DatabaseHelper INSTANCE = new DatabaseHelper();
    }
    
    public static DatabaseHelper getInstance() {
        return Holder.INSTANCE;
    }
}

优点

缺点

适用场景

Android 示例

// Application 类本身就是单例
public class MyApp extends Application {
    private static MyApp instance;
    
    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
    }
    
    public static MyApp getInstance() {
        return instance;
    }
}

// 使用单例
ImageLoader.getInstance().loadImage(url, imageView);

5. 依赖注入 (Dependency Injection)

名词解释

对象的依赖由外部容器提供,而不是自己创建,实现控制反转。

核心特点

// 手动依赖注入
public class UserRepository {
    private final ApiService apiService;
    
    public UserRepository(ApiService apiService) {
        this.apiService = apiService; // 依赖注入
    }
}

// 使用 Dagger/Hilt
@Module
@InstallIn(SingletonComponent.class)
public class NetworkModule {
    @Provides
    @Singleton
    public Retrofit provideRetrofit() {
        return new Retrofit.Builder()
            .baseUrl("https://api.example.com/")
            .addConverterFactory(GsonConverterFactory.create())
            .build();
    }
}

@AndroidEntryPoint
public class MainActivity extends AppCompatActivity {
    @Inject
    Retrofit retrofit; // 自动注入
}

优点

缺点

适用场景

Android 示例

// Hilt 注入 ViewModel
@HiltViewModel
public class MainViewModel extends ViewModel {
    private final UserRepository repository;
    
    @Inject
    public MainViewModel(UserRepository repository) {
        this.repository = repository;
    }
}

// Activity 中使用
@AndroidEntryPoint
public class MainActivity extends AppCompatActivity {
    @Inject
    MainViewModel viewModel;
}

6. 抽象工厂模式 (Abstract Factory Pattern)

名词解释

创建相关或依赖对象的家族,而不需要指定具体类。

核心特点

public interface ThemeFactory {
    Button createButton();
    TextView createTextView();
    Dialog createDialog();
}

public class LightThemeFactory implements ThemeFactory {
    @Override
    public Button createButton() {
        Button button = new Button(context);
        button.setBackgroundColor(Color.WHITE);
        return button;
    }
    // 其他方法...
}

public class DarkThemeFactory implements ThemeFactory {
    @Override
    public Button createButton() {
        Button button = new Button(context);
        button.setBackgroundColor(Color.BLACK);
        return button;
    }
    // 其他方法...
}

优点

缺点

适用场景

7. 原型模式 (Prototype Pattern)

名词解释

通过克隆现有对象来创建新实例,避免昂贵的初始化过程。

核心特点

public class UserProfile implements Cloneable {
    private String username;
    private Map<String, Object> preferences;
    
    public UserProfile(String username) {
        this.username = username;
        this.preferences = loadPreferences(); // 耗时操作
    }
    
    @Override
    public UserProfile clone() {
        try {
            UserProfile cloned = (UserProfile) super.clone();
            cloned.preferences = new HashMap<>(this.preferences); // 深拷贝
            return cloned;
        } catch (CloneNotSupportedException e) {
            throw new AssertionError();
        }
    }
}

// 使用
UserProfile original = new UserProfile("user123");
UserProfile copy = original.clone(); // 比 new 快很多

优点

缺点

适用场景

8. 反射创建 (Reflection)

名词解释

在运行时动态创建对象实例,通过类名等信息来实例化对象。

核心特点

public class ObjectFactory {
    public static <T> T createInstance(String className) {
        try {
            Class<?> clazz = Class.forName(className);
            return (T) clazz.newInstance();
        } catch (Exception e) {
            throw new RuntimeException("创建实例失败", e);
        }
    }
}

// 使用
String className = "com.example.MyClass";
MyClass obj = ObjectFactory.createInstance(className);

优点

缺点

适用场景

总结对比表

模式优点缺点适用场景使用频率
new 关键字简单、高性能、明确紧耦合、缺乏灵活性简单对象、内部使用⭐⭐⭐⭐⭐
静态工厂有名称、可控制、可缓存不能继承、不易发现需要控制创建逻辑⭐⭐⭐⭐
建造者参数灵活、可读性好代码冗余、创建开销多参数对象、配置复杂⭐⭐⭐
单例全局唯一、节省资源全局状态、测试困难全局管理、资源密集型⭐⭐⭐⭐
依赖注入解耦、易测试、生命周期管理学习曲线陡、调试复杂中大型项目、需要架构⭐⭐⭐⭐
抽象工厂产品族一致性、开闭原则复杂度高、难以扩展创建相关对象家族⭐⭐
原型性能优化、避免昂贵初始化深拷贝复杂、可能滥用创建成本高的相似对象
反射极度灵活、动态创建性能差、安全问题框架开发、插件系统

Android 开发建议

  1. 简单场景:优先使用 new 和静态工厂方法
  2. UI 组件:使用建造者模式(AlertDialog、Notification)
  3. 业务逻辑:使用依赖注入(Dagger/Hilt)
  4. 全局服务:谨慎使用单例模式,注意内存泄漏
  5. 性能敏感:考虑原型模式避免重复昂贵操作
  6. 框架开发:在必要时使用反射和抽象工厂

到此这篇关于Android/Java中创建类实例的各种模式的文章就介绍到这了,更多相关Java创建类实例模式内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文