核心区别总结
特性 |
object声明(具名单例) |
object表达式(匿名对象) |
实例数量 |
✅ 单例(全局唯一) |
❌ 每次创建新实例 |
声明位置 |
顶层或类内部) |
表达式位置 |
生命周期 |
应用级 |
局部作用域 |
使用场景 |
全局配置、工具类、策略常量 |
临时实现、回调、局部定制 |
详细对比代码
1. 具名单例对象 - 全局声明
object ImmediateStart : StartStrategy {
override operator fun invoke(block: suspend () -> Unit) {
println("ImmediateStart: ${this.hashCode()}")
}
}
2. 匿名对象表达式 - 局部创建
class TestClass {
fun testDifference() {
val anonymous1 = object : StartStrategy {
override operator fun invoke(block: suspend () -> Unit) {
println("Anonymous1: ${this.hashCode()}")
}
}
val anonymous2 = object : StartStrategy {
override operator fun invoke(block: suspend () -> Unit) {
println("Anonymous2: ${this.hashCode()}")
}
}
val singleton1 = ImmediateStart
val singleton2 = ImmediateStart
println("=== 单例对象测试 ===")
println("singleton1 === singleton2: ${singleton1 === singleton2}")
singleton1 { }
singleton2 { }
println("\n=== 匿名对象测试 ===")
println("anonymous1 === anonymous2: ${anonymous1 === anonymous2}")
anonymous1 { }
anonymous2 { }
}
}
字节码层面的区别
object
声明编译后
public final class ImmediateStart implements StartStrategy {
public static final ImmediateStart INSTANCE = new ImmediateStart();
private ImmediateStart() {}
}
object
表达式编译后
new StartStrategy() {
@Override
public Object invoke(Function0 block) {
}
}
实际应用场景对比
class NetworkManager {
companion object {
val DEFAULT_STRATEGY = ImmediateStart
}
fun createCustomStrategy(delay: Long): StartStrategy {
return object : StartStrategy {
override operator fun invoke(block: suspend () -> Unit) {
GlobalScope.launch {
delay(delay)
block()
}
}
}
}
fun demonstrateUsage() {
val strategy1 = DEFAULT_STRATEGY
val strategy2 = DEFAULT_STRATEGY
println("Same instance: ${strategy1 === strategy2}")
val custom1 = createCustomStrategy(1000)
val custom2 = createCustomStrategy(1000)
println("Different instances: ${custom1 === custom2}")
}
}
内存和性能影响
class PerformanceTest {
fun testMemoryUsage() {
repeat(1000) {
val strategy = ImmediateStart
}
repeat(1000) {
val strategy = object : StartStrategy {
override operator fun invoke(block: suspend () -> Unit) {}
}
}
}
}