重构组合模式示例,统一接口定义,增强代码可读性和一致性
This commit is contained in:
parent
86497cc06b
commit
9b51101c27
|
|
@ -7,25 +7,30 @@ import "fmt"
|
||||||
汤宝宝成为了上市集团老总,他们集团有好多好多家分公司...
|
汤宝宝成为了上市集团老总,他们集团有好多好多家分公司...
|
||||||
*/
|
*/
|
||||||
|
|
||||||
// 抽象接口
|
type component interface {
|
||||||
type Company interface {
|
|
||||||
// 显示公司名称
|
|
||||||
Show(prefix string)
|
Show(prefix string)
|
||||||
// 开设分公司
|
getName() string
|
||||||
Add(company Company)
|
|
||||||
// 分公司关门
|
|
||||||
Remove(company Company)
|
|
||||||
// 获取分公司
|
|
||||||
GetChild(i int) Company
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// 具体实现类
|
type Department struct {
|
||||||
type ConcreteCompany struct {
|
|
||||||
name string
|
name string
|
||||||
children []Company
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *ConcreteCompany) Show(prefix string) {
|
func (d *Department) Show(prefix string) {
|
||||||
|
fmt.Print(prefix)
|
||||||
|
fmt.Println(d.name)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Department) getName() string {
|
||||||
|
return d.name
|
||||||
|
}
|
||||||
|
|
||||||
|
type Company struct {
|
||||||
|
name string
|
||||||
|
children []component
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Company) Show(prefix string) {
|
||||||
fmt.Print(prefix)
|
fmt.Print(prefix)
|
||||||
fmt.Println(c.name)
|
fmt.Println(c.name)
|
||||||
for _, child := range c.children {
|
for _, child := range c.children {
|
||||||
|
|
@ -33,22 +38,26 @@ func (c *ConcreteCompany) Show(prefix string) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *ConcreteCompany) Add(company Company) {
|
func (c *Company) getName() string {
|
||||||
c.children = append(c.children, company)
|
return c.name
|
||||||
fmt.Printf("在%s下开设了分公司%s\n", c.name, company.(*ConcreteCompany).name)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *ConcreteCompany) Remove(company Company) {
|
func (c *Company) Add(company component) {
|
||||||
|
c.children = append(c.children, company)
|
||||||
|
fmt.Printf("在%s下开设了%s\n", c.name, company.getName())
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Company) Remove(company component) {
|
||||||
for i, child := range c.children {
|
for i, child := range c.children {
|
||||||
if child == company {
|
if child == company {
|
||||||
c.children = append(c.children[:i], c.children[i+1:]...)
|
c.children = append(c.children[:i], c.children[i+1:]...)
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
fmt.Printf("在%s下关闭了分公司%s\n", c.name, company.(*ConcreteCompany).name)
|
fmt.Printf("在%s下裁撤了%s\n", c.name, company.getName())
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *ConcreteCompany) GetChild(i int) Company {
|
func (c *Company) GetChild(i int) component {
|
||||||
if i < 0 || i >= len(c.children) {
|
if i < 0 || i >= len(c.children) {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
@ -58,12 +67,12 @@ func (c *ConcreteCompany) GetChild(i int) Company {
|
||||||
func main() {
|
func main() {
|
||||||
fmt.Println("============= 组合模式 =============")
|
fmt.Println("============= 组合模式 =============")
|
||||||
|
|
||||||
headOffice := &ConcreteCompany{name: "汤氏总公司"}
|
headOffice := &Company{name: "汤氏总公司"}
|
||||||
headOffice.Add(&ConcreteCompany{name: "汤氏A分公司"})
|
headOffice.Add(&Company{name: "汤氏A分公司"})
|
||||||
headOffice.Add(&ConcreteCompany{name: "汤氏B分公司"})
|
headOffice.Add(&Department{name: "人事部"})
|
||||||
headOffice.Add(&ConcreteCompany{name: "汤氏C分公司"})
|
headOffice.Add(&Department{name: "研发部"})
|
||||||
headOffice.GetChild(0).Add(&ConcreteCompany{name: "汤氏A分公司-子公司1"})
|
headOffice.GetChild(0).(*Company).Add(&Department{name: "市场部"})
|
||||||
headOffice.GetChild(0).Add(&ConcreteCompany{name: "汤氏A分公司-子公司2"})
|
headOffice.GetChild(0).(*Company).Add(&Department{name: "财务部"})
|
||||||
headOffice.Remove(headOffice.GetChild(2))
|
headOffice.Remove(headOffice.GetChild(2))
|
||||||
fmt.Println()
|
fmt.Println()
|
||||||
headOffice.Show("~ ")
|
headOffice.Show("~ ")
|
||||||
|
|
|
||||||
|
|
@ -6,32 +6,31 @@
|
||||||
from abc import ABC, abstractmethod
|
from abc import ABC, abstractmethod
|
||||||
|
|
||||||
|
|
||||||
# 抽象类
|
# 接口
|
||||||
class Company(ABC):
|
class component(ABC):
|
||||||
name: str
|
name: str
|
||||||
children: list["Company"]
|
|
||||||
|
|
||||||
@abstractmethod
|
@abstractmethod
|
||||||
def show(self, prefix: str) -> None:
|
def show(self, prefix: str) -> None:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
@abstractmethod
|
|
||||||
def add(self, company: "Company") -> None:
|
|
||||||
pass
|
|
||||||
|
|
||||||
@abstractmethod
|
# 具体类
|
||||||
def remove(self, company: "Company") -> None:
|
class Department(component):
|
||||||
pass
|
|
||||||
|
|
||||||
@abstractmethod
|
|
||||||
def get_child(self, index: int) -> "Company":
|
|
||||||
pass
|
|
||||||
|
|
||||||
|
|
||||||
# 实现类
|
|
||||||
class ConcreteCompany(Company):
|
|
||||||
name: str
|
name: str
|
||||||
children: list[Company]
|
|
||||||
|
def __init__(self, name: str) -> None:
|
||||||
|
self.name = name
|
||||||
|
|
||||||
|
def show(self, prefix: str) -> None:
|
||||||
|
print(f"{prefix}{self.name}")
|
||||||
|
|
||||||
|
# 实现类
|
||||||
|
|
||||||
|
|
||||||
|
class Company(component):
|
||||||
|
name: str
|
||||||
|
children: list[component]
|
||||||
|
|
||||||
def __init__(self, name: str) -> None:
|
def __init__(self, name: str) -> None:
|
||||||
self.name = name
|
self.name = name
|
||||||
|
|
@ -42,15 +41,15 @@ class ConcreteCompany(Company):
|
||||||
for child in self.children:
|
for child in self.children:
|
||||||
child.show(f"{prefix}-> ")
|
child.show(f"{prefix}-> ")
|
||||||
|
|
||||||
def add(self, company: Company) -> None:
|
def add(self, company: component) -> None:
|
||||||
self.children.append(company)
|
self.children.append(company)
|
||||||
print(f"在{self.name}下开设了分公司{company.name}")
|
print(f"在{self.name}下开设了{company.name}")
|
||||||
|
|
||||||
def remove(self, company: Company) -> None:
|
def remove(self, company: component) -> None:
|
||||||
self.children.remove(company)
|
self.children.remove(company)
|
||||||
print(f"在{self.name}下关闭了分公司{company.name}")
|
print(f"在{self.name}下裁撤了{company.name}")
|
||||||
|
|
||||||
def get_child(self, index: int) -> Company:
|
def get_child(self, index: int) -> component:
|
||||||
if index < 0 or index >= len(self.children):
|
if index < 0 or index >= len(self.children):
|
||||||
raise IndexError("子公司索引超出范围")
|
raise IndexError("子公司索引超出范围")
|
||||||
return self.children[index]
|
return self.children[index]
|
||||||
|
|
@ -59,12 +58,14 @@ class ConcreteCompany(Company):
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
print("============= 组合模式 =============")
|
print("============= 组合模式 =============")
|
||||||
|
|
||||||
head_office = ConcreteCompany("汤氏总公司")
|
head_office = Company("汤氏总公司")
|
||||||
head_office.add(ConcreteCompany("汤氏A分公司"))
|
head_office.add(Company("汤氏A分公司"))
|
||||||
head_office.add(ConcreteCompany("汤氏B分公司"))
|
head_office.add(Department("人事部"))
|
||||||
head_office.add(ConcreteCompany("汤氏C分公司"))
|
head_office.add(Department("研发部"))
|
||||||
head_office.get_child(0).add(ConcreteCompany("汤氏A分公司-子公司1"))
|
child = head_office.get_child(0)
|
||||||
head_office.get_child(0).add(ConcreteCompany("汤氏A分公司-子公司2"))
|
if isinstance(child, Company):
|
||||||
|
child.add(Department("市场部"))
|
||||||
|
child.add(Department("财务部"))
|
||||||
head_office.remove(head_office.get_child(2))
|
head_office.remove(head_office.get_child(2))
|
||||||
print("\n")
|
print("\n")
|
||||||
head_office.show("~ ")
|
head_office.show("~ ")
|
||||||
|
|
|
||||||
|
|
@ -3,16 +3,22 @@
|
||||||
汤宝宝成为了上市集团老总,他们集团有好多好多家分公司...
|
汤宝宝成为了上市集团老总,他们集团有好多好多家分公司...
|
||||||
*/
|
*/
|
||||||
|
|
||||||
interface Company {
|
interface component {
|
||||||
name: string;
|
name: string;
|
||||||
children: Company[];
|
|
||||||
show(prefix: string): void;
|
show(prefix: string): void;
|
||||||
add(company: Company): void;
|
|
||||||
remove(company: Company): void;
|
|
||||||
getChild(index: number): Company | undefined;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
class ConcreteCompany implements Company {
|
class Department implements component {
|
||||||
|
name: string;
|
||||||
|
constructor(name: string) {
|
||||||
|
this.name = name;
|
||||||
|
}
|
||||||
|
show(prefix: string): void {
|
||||||
|
console.log(prefix + this.name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class Company implements component {
|
||||||
name: string;
|
name: string;
|
||||||
children: Company[] = [];
|
children: Company[] = [];
|
||||||
constructor(name: string) {
|
constructor(name: string) {
|
||||||
|
|
@ -24,18 +30,18 @@ class ConcreteCompany implements Company {
|
||||||
child.show(prefix + "-> ");
|
child.show(prefix + "-> ");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
add(company: Company): void {
|
add(company: component): void {
|
||||||
this.children.push(company);
|
this.children.push(company as Company);
|
||||||
console.log(`在${this.name}下开设了分公司${company.name}`);
|
console.log(`在${this.name}下开设了${company.name}`);
|
||||||
}
|
}
|
||||||
remove(company: Company): void {
|
remove(company: component): void {
|
||||||
const index = this.children.indexOf(company);
|
const index = this.children.indexOf(company as Company);
|
||||||
if (index !== -1) {
|
if (index !== -1) {
|
||||||
this.children.splice(index, 1);
|
this.children.splice(index, 1);
|
||||||
}
|
}
|
||||||
console.log(`在${this.name}下关闭了分公司${company.name}`);
|
console.log(`在${this.name}下裁撤了${company.name}`);
|
||||||
}
|
}
|
||||||
getChild(index: number): Company | undefined {
|
getChild(index: number): component {
|
||||||
return this.children[index];
|
return this.children[index];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -43,12 +49,15 @@ class ConcreteCompany implements Company {
|
||||||
(function () {
|
(function () {
|
||||||
console.log("============= 组合模式 =============");
|
console.log("============= 组合模式 =============");
|
||||||
|
|
||||||
const headOffice = new ConcreteCompany("总公司");
|
const headOffice = new Company("总公司");
|
||||||
headOffice.add(new ConcreteCompany("汤氏A分公司"));
|
headOffice.add(new Company("汤氏A分公司"));
|
||||||
headOffice.add(new ConcreteCompany("汤氏B分公司"));
|
headOffice.add(new Department("人事部"));
|
||||||
headOffice.add(new ConcreteCompany("汤氏C分公司"));
|
headOffice.add(new Department("研发部"));
|
||||||
headOffice.getChild(0)?.add(new ConcreteCompany("汤氏A分公司-子公司1"));
|
const child = headOffice.getChild(0);
|
||||||
headOffice.getChild(0)?.add(new ConcreteCompany("汤氏A分公司-子公司2"));
|
if (child instanceof Company) {
|
||||||
|
child.add(new Department("市场部"));
|
||||||
|
child.add(new Department("财务部"));
|
||||||
|
}
|
||||||
headOffice.remove(headOffice.getChild(2)!);
|
headOffice.remove(headOffice.getChild(2)!);
|
||||||
|
|
||||||
console.log();
|
console.log();
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue