组合模式

master
robin(lc) 3 years ago
parent 49899fac8f
commit 63402cc583

@ -0,0 +1,24 @@
package org.alis.smallcc.designpatterns.structure.composite;
/**
*
*
* @author robin
* @date 2022/5/9 17:52
*/
public interface Component {
/**
*
*/
void operation();
/**
*
*
* @param component
*/
void addComponent(Component component);
}

@ -0,0 +1,26 @@
package org.alis.smallcc.designpatterns.structure.composite;
import java.util.ArrayList;
import java.util.List;
/**
* @author lc
* @date 2022/5/9 17:51
*/
public class Composite implements Component {
private final List<Component> COMPONENT_LIST = new ArrayList<>();
@Override
public void operation() {
System.out.println("\n" + hashCode() + " 组合器执行:\n");
for (Component component : COMPONENT_LIST) {
component.operation();
}
}
@Override
public void addComponent(Component component) {
COMPONENT_LIST.add(component);
}
}

@ -0,0 +1,17 @@
package org.alis.smallcc.designpatterns.structure.composite;
/**
* @author lc
* @date 2022/5/9 17:57
*/
public class LazyComponent implements Component {
@Override
public void operation() {
System.out.println(hashCode() + "懒惰节点执行");
}
@Override
public void addComponent(Component component) {
throw new UnsupportedOperationException();
}
}

@ -0,0 +1,32 @@
package org.alis.smallcc.designpatterns.structure.composite;
import java.util.concurrent.ThreadLocalRandom;
/**
* @author lc
* @date 2022/5/9 18:00
*/
public class Main {
public static void main(String[] args) {
// 创建一个根
Component root = new Composite();
for (int i = 0; i < 3; i++) {
Composite composite = new Composite();
// 创建10个懒惰或者勤快节点
for (int j = 0; j < 10; j++) {
int i1 = ThreadLocalRandom.current().nextInt(0, 10);
Component component;
if (i1 % 2 == 0) {
component = new WorkComponent();
} else {
component = new LazyComponent();
}
composite.addComponent(component);
}
root.addComponent(composite);
}
root.operation();
}
}

@ -0,0 +1,10 @@
package org.alis.smallcc.designpatterns.structure.composite;
/**
*
*
* @author lc
* @date 2022/5/9 17:51
*/
public class PackageInfo {
}

@ -0,0 +1,17 @@
package org.alis.smallcc.designpatterns.structure.composite;
/**
* @author lc
* @date 2022/5/9 17:57
*/
public class WorkComponent implements Component {
@Override
public void operation() {
System.out.println(hashCode() + "工作节点执行");
}
@Override
public void addComponent(Component component) {
throw new UnsupportedOperationException();
}
}
Loading…
Cancel
Save