1. 代理模式
public interface Company {
void developSoftware();
}
public class ProductCompany implements Company {
private Company compay;
public ProductCompany(Company company) {
this.compay = company;
}
@Override
public void developSoftware() {
this.compay.developSoftware();
}
}
public class SoftwareCompany implements Company {
@Override
public void developSoftware() {
System.out.println("软件公司开发软件。。。");
}
}
public class Customer {
public static void main(String[] args) {
ProductCompany productCompany = new ProductCompany(new SoftwareCompany());
productCompany.developSoftware();
}
}
2. 门面模式
public class Researcher {
public void writeThesis() {
System.out.println("写论文......");
}
public void publishThesis() {
System.out.println("发表论文......");
}
}
public class Supervisor {
public void guideThesis() {
System.out.println("指导写论文......");
}
public void checkThesis() {
System.out.println("检查论文......");
}
}
public class ThesisProcess {
private Researcher researcher = new Researcher();
private Supervisor supervisor = new Supervisor();
public void publishThesis() {
researcher.writeThesis();
supervisor.guideThesis();
supervisor.checkThesis();
researcher.publishThesis();
}
}
public class College {
public static void main(String[] args) {
ThesisProcess thesisProcess = new ThesisProcess();
thesisProcess.publishThesis();
}
}
3. 观察者模式
public class LiSi implements Observer {
@Override
public void update(Observable o, Object arg) {
System.out.println("LiSi汇报:" + arg);
}
}
public class ZhaoGao implements Observer {
@Override
public void update(Observable o, Object arg) {
System.out.println("ZhaoGao报告:" + arg);
}
}
public class HanFeiZi extends Observable {
public void activity(String name) {
super.setChanged();
super.notifyObservers("HanFeiZi去了" + name + "!");
}
}
public class Client {
public static void main(String[] args) {
HanFeiZi hfz = new HanFeiZi();
hfz.addObserver(new LiSi());
hfz.addObserver(new ZhaoGao());
hfz.activity("紫兰轩");
}
}
4. 策略模式
public interface IStrategy {
void operate();
}
public class FirstStrategy implements IStrategy{
@Override
public void operate() {
System.out.println("打开第一个锦囊妙计");
}
}
public class SecondStrategy implements IStrategy{
@Override
public void operate() {
System.out.println("打开第二个锦囊妙计");
}
}
public class ThirdStrategy implements IStrategy{
@Override
public void operate() {
System.out.println("打开第三个锦囊妙计");
}
}
public class Context {
private IStrategy strategy;
public Context(IStrategy strategy) {
this.strategy = strategy;
}
public void operate() {
strategy.operate();
}
}
public class Executor {
public static void main(String[] args) {
Context context = null;
context = new Context(new FirstStrategy());
context.operate();
context = new Context(new SecondStrategy());
context.operate();
context = new Context(new ThirdStrategy());
context.operate();
}
}