go java python 面向对象区别

接口的常见用法

  1. 多态:不同类型实现同一接口,实现多态行为。
  2. 解耦:通过接口定义依赖关系,降低模块之间的耦合。
  3. 泛化:使用空接口 interface{} 表示任意类型。

 

 
 
特性JavaPythonGo
类的定义 必须有,严格层次 有,灵活 无类,只有结构体
继承方式 单继承,多接口实现 多继承 不支持,组合替代
多态 显式接口/继承 鸭子类型 隐式接口
设计哲学 高度结构化 动态、简单 组合优于继承
适用场景 企业级大型系统 AI、脚本、Web 网络服务、高并发
简而言之,Java 是经典 OOP,Python 是自由 OOP,Go 是以组合和接口为核心的非传统 OOP。

 

 

 

go 接口 策略模式

package main

import "fmt"

type PaymentStrategy interface {
Pay(amount float64) error
}

type CreditCard struct {
Number string
}

func (cc CreditCard) Pay(amount float64) error {
fmt.Printf("Paid $%.2f with credit card %s\n", amount, cc.Number)
return nil
}

type PayPal struct {
Email string
}

func (pp PayPal) Pay(amount float64) error {
fmt.Printf("Paid $%.2f via PayPal (%s)\n", amount, pp.Email)
return nil
}

type Order struct {
Amount float64
Strategy PaymentStrategy
}

func (o Order) Checkout() error {
return o.Strategy.Pay(o.Amount)
}

func main() {
order := Order{
Amount: 99.99,
Strategy: CreditCard{Number: "1234-5678"},
}
order.Checkout() // Paid $99.99 with credit card 1234-5678

order.Strategy = PayPal{Email: "user@example.com"}
order.Checkout() // Paid $99.99 via PayPal (user@example.com)
}

 

适配器模式

package main

import (
"fmt"
"os"
)

type Logger interface {
Log(message string)
}

type ConsoleLogger struct{}

func (cl ConsoleLogger) Log(message string) {
fmt.Println("[CONSOLE]", message)
}

type FileLogger struct {
File *os.File
}

func (fl FileLogger) Log(message string) {
fl.File.WriteString(message + "\n")
}

// 适配函数
type LogFunc func(string)

func (lf LogFunc) Log(message string) {
lf(message)
}

func main() {
// 使用函数作为适配器
logger := LogFunc(func(msg string) {
fmt.Println("[CUSTOM]", msg)
})
logger.Log("Hello")

logger1 := ConsoleLogger{}
logger1.Log("Hello")
}

 

// 1. 结构体 (Struct) - 替代类
type Person struct {
Name string
Age int
}

// 方法绑定到结构体
func (p Person) SayHello() string {
return fmt.Sprintf("Hello, my name is %s", p.Name)
}

// 2. 组合 - 替代继承
type Animal struct {
Name string
}

func (a Animal) Speak() string {
return "..."
}

type Dog struct {
Animal // 嵌入结构体,实现组合
Breed string
}

// Dog 自动拥有 Animal 的方法
dog := Dog{Animal: Animal{Name: "Buddy"}, Breed: "Labrador"}
fmt.Println(dog.Speak()) // 可以调用 Animal 的方法

# 3. 接口 (Interface) - 多态
type Speaker interface {
Speak() string
}

type Cat struct {
Name string
}

func (c Cat) Speak() string {
return "Meow"
}

// 隐式实现接口,无需显式声明
func MakeSound(s Speaker) {
fmt.Println(s.Speak())
}

MakeSound(Dog{}) // 输出: ...
MakeSound(Cat{}) // 输出: Meow

# 4. 封装 - 通过大小写控制可见性
type Account struct {
balance float64 // 小写开头,私有字段
Owner string // 大写开头,公有字段
}

// 公有方法访问私有字段
func (a *Account) Deposit(amount float64) {
a.balance += amount
}

func (a *Account) GetBalance() float64 {
return a.balance
}

 

 

传统 OOP
Go 的实现方式
类 (Class)
结构体 (Struct)


继承 (Inheritance)
组合/嵌入 (Composition/Embedding)


多态 (Polymorphism)
接口 (Interface)


封装 (Encapsulation)
大小写控制可见性


方法重载
不支持(使用不同函数名)

 

 

 

posted @ 2026-04-09 21:57  papering  阅读(4)  评论(0)    收藏  举报