簡述
- 創(chuàng)建型設計模式
- 顧名思義祝迂,工廠模式是創(chuàng)建一個產(chǎn)品的工廠姐军,根絕不同類型創(chuàng)建不同實例
實現(xiàn)方式
- 使用三方分享做演示撵颊, 三方分享不做重點實現(xiàn)宇攻,用偽代碼代替
// 提供產(chǎn)品的抽象類
public class IShareService {
fun share(context : Context, shareText: String, callback ShareCallback)
fun destroy()
}
// 分享結果的回調
public interface ShareCallback{
fun success(text: String)
fun feild(text: String)
fun cancel()
}
// 分享渠道 如:微信,QQ
public enum ShareType {
WeChat,
QQ // 此處可以任意擴展
}
// 實現(xiàn)QQ分享
public class QQShareService : IShareService {
override fun share(context: Context, shareText: String, callback: ShareCallback) {
// 此處做分享操作. 關注分享回調
QQShare.share().callback() {
fun success(text: String) {
callback.success(text)
}
fun feild(text: String) {
callback.feild(text)
}
fun cancel() {
callback.cancel()
}
}
}
override fun destroy() {
// 釋放資源
}
}
// 實現(xiàn)微信分享
public class WeChatShareService : IShareService {
override fun share(context: Context, shareText: String, callback: ShareCallback) {
// 此處做分享操作. 關注分享回調
WeChat.share().callback() {
fun success(text: String) {
callback.success(text)
}
fun feild(text: String) {
callback.feild(text)
}
fun cancel() {
callback.cancel()
}
}
}
override fun destroy() {
// 釋放資源
}
}
// 提供分享實例
public object IShareFactory {
fun createShareService(shareType: ShareType): IShareService {
var iShareType:IShareService? = null
when(shareType) {
ShareType.QQ -> iShareType = QQShareService()
ShareType.WeChat -> iShareType = WeChatShareService()
}
if (iShareType == null) {
throw RuntimeException("創(chuàng)建實例失敗倡勇,檢查分享類型")
}
return iShareType!!
}
}
// 使用方式
class MainActivity : AppCompatActivity() {
private var iShareServie: IShareService? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
override fun onClick(view: View?) {
when(view?.id) {
R.id.qq->{
share(ShareType.QQ)
}
R.id.wechat->{
share(ShareType.WeChat)
}
}
}
private share(shareType: ShareType) {
iShareServie = IShareFactory. createShareService(shareType)
iShareServie?.share(this, "分享內容", object: ShareCallback {
fun success(text: String) {
// 分享成功
}
fun feild(text: String) {
// 分享失敗
}
fun cancel() {
// 分享取消
}
})
}
override fun onDestroy() {
// 銷毀
iShareServie?.destroy()
}
}