编程技巧:Mixin(行为继承)

C#

C#通过为类和接口提供扩展方法来实现行为继承。

interface SampleMixin {}
static class SampleExtension {
	static void SampleMethod(this SampleMixin m) {
		Console.WriteLine("default implementation");
	}
	static void SampleMethod2(this SampleClass c) {
		Console.WriteLine("default implementation2");
	}
}
class SampleClass : SampleMixin {}
new SampleClass().SampleMethod(); // default implementation
new SampleClass().SampleMethod2(); // default implementation2

Java

Java通过接口的缺省方法来实现行为继承。

interface SampleMixin {
	default void sampleMethod() {
		System.out.println("default implementation");
	}
}
class SampleClass implements SampleMixin {}
new SampleClass().sampleMethod(); // default implementation

Swift

Swift通过对协议进行扩展来实现行为继承。

protocol SampleMixin {
	func sampleMethod()
}
extension SampleMixin {
	func sampleMethod() {
		print("default implementation")
	}
}
class SampleClass : SampleMixin {} 
SampleClass().sampleMethod() // default implementation

你可能感兴趣的:(编程技巧)